2012-04-17 13:37:42  浏览:2322

cakephp

cakephp 开源的php框架,支持 MVC、Rrest风格

app/Config/core.php设置

Configure::write('debug', 2);

Configure::write('App.encoding', 'UTF-8');

app/config/database.php 配置数据库


public $default = array (

'datasource' => 'Database/Mysql',

'persistent' => false, // 是否使用持久化

'host' => 'localhost',

'login' => 'root',

'password' => '111111',

'database' => 'test',

'prefix' => 't_',//可要可不要

// 'encoding' => 'utf8' 

);


app/Config/routes.php 或者lib/Cake/Config/routes.php修改请求路由

Router::connect('/:name/:ver/:controller/:action/page::page/*',array(),array('name'=>'[0-9a-z]+','ver'=>'[0-9a-z]+','id'=>'[0-9]+','page'=>'[0-9]+'));

例子:/snoopy/v1/products(控制器)/display(请求的方法)/page:2(分页页码)


控制器中的分页查询

//定义为全局变量


var $paginate = array (

'Product' => array (

'limit' => 18,

'order' => array (

'Product.id' => 'desc' 

),

'Category' => array () 

);

//写入到要请求的方法中


$data = $this->paginate ( "Product" );

如果需要用到级联查询,可要用






hasMany 一对多         

hasOne   一对一        主表主键对应字表外键

belongsTo  多对一     主表外键对应字表主键

hasAndBelongsToMany 多对多





需要在app/model下定义模型,

定义Catagory和Product两个模型

在Product中写


var $belongsTo  = array (

'Catagory' => array (

'className' => 'Category',

'foreignKey' => 'cat_id',

'fields' => array (
'id',

'cat_name' 

)

;



hasOne关联支持的键包括:



belongsTo关联数组的键选项有:




hasMany关联数组的键选项有:

  • className: 需要关联模型的类名。如果定义了'User hasMany Comment’关联,className键值应为'Comment’。
  • foreignKey: 需要关联模型的外键名称。此键对于定义多个hasMany关联时尤其有用。该键的默认值为当前模型的下划线、单数表示名称,加上'_id’后缀。
  • conditions: 一段SQL代码用来过滤模型记录。在SQL代码中加上模型名称是个好习惯:如“Comment.status = 1”就比“status = 1”要好。
  • fields: 取得关联数据的字段列表。默认返回所有字段。
  • order: SQL代码段,定义返回的关联数据的排序。
  • limit: 返回的关联数据的最大行数。
  • offset: 在读取和关联之前需要跳过的关联记录的行数(以当前的条件和排序为准)。
  • dependent: 当dependent设置为true时,递归删除生效。举例,当用户记录被删除时,关联的Comment记录也会随之而删除。

    要使递归删除生效,Model->delete()方法的第二个参数必须设置为ture。

  • exclusive: 当exclusive设置为true时,递归删除会使用deleteAll()调用进行删除,而不逐个的进行删除。此方法会大幅提升性能,但不一定对所有环境都有效。
  • finderQuery: 一条完整的SQL语句,CakePHP可以用来读取关联模型记录。该情况适用于那些需要特定查询结果的情形。



Possible keys for HABTM association arrays include:

  • className: the classname of the model being associated to the current model. If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
  • joinTable: The name of the join table used in this association (if the current table doesn't adhere to the naming convention for HABTM join tables).
  • with: Defines the name of the model for the join table. By default CakePHP will auto-create a model for you. Using the example above it would be called RecipesTag. By using this key you can override this default name. The join table model can be used just like any "regular" model to access the join table directly.
  • foreignKey: the name of the foreign key found in the current model. This is especially handy if you need to define multiple HABTM relationships. The default value for this key is the underscored, singular name of the current model, suffixed with '_id'.
  • associationForeignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple HABTM relationships. The default value for this key is the underscored, singular name of the other model, suffixed with '_id'.
  • unique: If true (default value) cake will first delete existing relationship records in the foreign keys table before inserting new ones, when updating a record. So existing associations need to be passed again when updating.
  • conditions: An SQL fragment used to filter related model records. It's good practice to use model names in SQL fragments: "Comment.status = 1" is always better than just "status = 1."
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • limit: The maximum number of associated rows you want returned.
  • offset: The number of associated rows to skip over (given the current conditions and order) before fetching and associating.
  • finderQuery, deleteQuery, insertQuery: A complete SQL query CakePHP can use to fetch, delete, or create new associated model records. This should be used in situations that require very custom results.


不太好理解的hasAndBelongsToMany关联(多对多关联)

我们的数据表结构如下

01. --用户表
02.  
03. CREATE TABLE IF NOT EXISTS `users` (
04. `id` int(11) NOT NULL auto_increment,
05. `name` varchar(60) collate utf8_unicode_ci NOT NULL,
06. `username` varchar(20) collate utf8_unicode_ci NOT NULL,
07. `password` varchar(255) collate utf8_unicode_ci NOT NULL,
08. `created` datetime NOT NULL,
09. PRIMARY KEY  (`id`)
10. ) ENGINE=MyISAM;
11.  
12. --用户和好友关联表
13.  
14. CREATE TABLE IF NOT EXISTS `friends_users` (
15. `id` bigint(10) NOT NULL auto_increment,
16. `user_id` bigint(10) NOT NULL,
17. `friend_id` bigint(10) NOT NULL,
18. PRIMARY KEY  (`id`)
19. ) ENGINE=MyISAM;

我们需要建立三个模型类

User模型,对应于users表,文件/app/models/user.php

1. class User extends AppModel{
2. var $name = 'User';
3.  
4. var $hasAndBelongsToMany = array(
5. 'Friend' => array('with' => 'FriendsUser')
6. );
7.  
8. }

Friend模型,也对应users表(Friend和User共享数据),用来和users模型进行多对多关联

文件/app/models/friend.php

1. class Friend extends AppModel {
2. var $name = 'Friend';
3. var $useTable = 'users';
4. var $hasAndBelongsTo = array(
5. 'User' => array('with' => 'FriendsUser')
6. );
7. }

FriendsUser模型,对应关联表friends_users,文件/app/models/friends_user.php

1. class FriendsUser extends AppModel {
2. var $name = 'FriendsUser';
3. var $belongsTo = array('Friend','User');
4. }

好了,定义好模型,我们要查询User的所有Friend,在控制器中,要这样

01. class UsersController extends AppController {
02. var $name = 'Users';
03.  
04. //这里,我们要引入这三个模型,如果你有更多的模型,可以一起引入
05. var $uses = array('User','Friend','FriendsUser');
06.  
07. function test(){
08. $conditions = array(
09. 'User.id' => 1
10. );
11. $contain = array('User','Friend');
12. $fields = array(
13. 'User.id',
14. 'User.name',
15. 'Friend.id',
16. 'Friend.name'
17. );
18. $limit = 5;
19.  
20. //我们使用了中间表FriendsUser,来查询,compact函数是cakephp提倡的用法
21. $data = $this->FriendsUser->find('all',compact(
22. 'conditions',
23. 'contain',
24. 'fields',
25. 'limit'
26. ));
27.  
28. debug($data);
29. exit;
30. }
31. }

查询的结果,可能类似下面的数据

01. Array
02. (
03. [0] => Array
04. (
05. [User] => Array
06. (
07. [id] => 1
08. [name] => Drake Duran
09. )
10.  
11. [Friend] => Array
12. (
13. [id] => 2
14. [name] => Dane Knowles
15. )
16.  
17. )
18.  
19. [1] => Array
20. (
21. [User] => Array
22. (
23. [id] => 1
24. [name] => Drake Duran
25. )
26.  
27. [Friend] => Array
28. (
29. [id] => 3
30. [name] => Felix Kelley
31. )
32.  
33. )
34.  
35. )


可以看到,这正是我们需要的数据。


参考文档:

http://book.cakephp.org/1.3/cn/view/1044/hasAndBelongsToMany-HABTM

http://my.oschina.net/adamboy/blog/17596










返回首页