Oct 8

Cakephp的belongs,hasOne,hasMany,hasAndbelongsToMany中的详细用法 不指定

bkkkd , 20:56 , 开发应用 , 评论(0) , 引用(0) , 阅读(10920) , Via 本站原创 | |
今天我遇到了一个问题,需要 left join .苦于教程中未有提及如何belongsTo同一张表两次.所以只有自己做了测试.如下的两张表:
用户表
id|name|create|
留言表
id|feedback_user_id|reply_user_id|subject|feedback|reply|
由于这里的feedback_user_id与reply_user_id都需要用引用户表.所以我们需要将 left join 用户表两次.按照教程里说的,很容易犯一个错误.那就是以为 belongsTo 的下标一定是跟classname一样.其实事实不是这样.belongsTo的介绍没有写详细用法.

var $belongsTo = array(
                                'FeedbackUser' =>array(
                         'className'  => 'User',
                         'conditions' => '',
                                           'order'      => '',
                   'foreignKey' => 'feedback_user_id'
                   )
                               'ReplykUser' =>array(
                         'className'  => 'User',
                         'conditions' => '',
                                           'order'      => '',
                   'foreignKey' => 'feedback_user_id'
                   )
                       );
}

用belongsTo的下标不是指是model的className.是指定数据表的别名.因此,belongs,hasOne,hasMany,hasAndbelongsToMany在定义的时候,可以重新定义数据表的别名不一定要跟着系统默认的表名做.
以下是cakephp的关于belongsTo
引用

现在User对象能够得到对应的Profile对象,当然我们也应该为Profile对象定义一个关联使之能够获取它的所有者,也就是对应的User对象。在Cake中,我们使用belongsTo关联来实现:

/app/models/profile.php belongsTo  
<?php  class Profile extends AppModel  {
var $name = 'Profile';
var $belongsTo = array('User' =>
                            array(
                 'className'  => 'User',
                 'conditions' => '',
                                   'order'      => '',
           'foreignKey' => 'user_id'
           )
                       );
}
?>

和hasOne关联一样,belongsTo也是一个array变量,你可以通过设置其中的值来具体定义belongsTo关联:
[li]className (required): 关联对象的类名,这里我们关联的是User对象,所以应该是'User'。
[li]conditions: SQL条件子句以限定关联的对象,假定我们只允许Profile关联状态为active的用户,我们可以这样写:"User.active = '1'",当然也可以是类似的其它条件。
[li]order:关联对象的排序子句,假如你希望关联的对象经过排序,你可以类似"User.last_name ASC"这样来定义。
[li]foreignKey:关联对象所对应的外键字段名,仅在你不遵循Cake的命名约定时需要设置。
现在当我们使用find() findAll()来检索Profile对象时,会发现关联的User对象也一同被检索回来。

$profile = $this->Profile->read(null, '4');
print_r($profile);
//output:
Array  (
        [Profile] => Array(
                     [id] => 4
                     [name] => Cool Blue
                     [header_color] => aquamarine
                     [user_id] = 25
         )
  [User] => Array(
         [id] => 25
         [first_name] => John
         [last_name] => Anderson
         [username] => psychic
         [password] => c4k3roxx
      )
  )

Tags: ,
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]