CakePHP - 如何检索深层关联的数据? [英] CakePHP - How to retrieve deeply associated data?
问题描述
我有以下型号:
用户:
- hasOne个人资料页面
- 有多个评论
- belongsTo用户,信息页,个人资料
第
页: 评论个人资料:
- belongsTo User
当我检索页面时,我想获得相关的评论,
我的注释表有字段page_id和user_id。
我的个人资料表有user_id。
所以,我假设我需要做一些事情。
注释belongsTo
'Profile'=> array(
'conditions'=> array('Profile.user_id'=>'Comment.user_id')
)
但这不工作 - 它返回一个空白的配置文件记录。
任何人都可以帮助?我要圆圈! (使用CakePHP 2.0)
使用CakePHP的可容纳的行为[link] 。基本上,这允许你选择你想要包含在你的查找中的相关模型。
你也可以从每个模型中指定你想要的字段,
code> // PageModel
public $ actsAs = array('Containable');
public function getPage($ id = null){
$ this-> recursive = -1; //通常在AppModel中设置为-1,以使默认值为
$ this-> find('all',array(
'conditions'=> array(
' page.id'=> $ id
),
'包含'=> array(
'注释'=> array(
'User'=> array (
'Profile',
),
),
)
));
}
I have the following models:
User:
- hasOne Profile, Page
- hasMany Comment
Comment:
- belongsTo User, Page, Profile
Page:
- belongsTo User
- hasMany Comment
Profile:
- belongsTo User
When I retrieve a page, I want to get the associated Comments, and for each comment I want the Profile.
My comments table has fields page_id and user_id. My profile table has user_id.
So, I assume I need to do something like
Comment belongsTo
'Profile' => array(
'conditions' => array('Profile.user_id' => 'Comment.user_id')
)
but that's not working - it returns a blank profile record.
Can anyone help? I'm going round in circles! (using CakePHP 2.0)
Use CakePHP's Containable behavior [link]. Basically, this allows you to pick and choose which related models you want to include in your find.
You can also specify which field(s) you want from each model, specify conditions on each...etc.
It should look something like this:
//PageModel
public $actsAs = array('Containable');
public function getPage($id=null) {
$this->recursive = -1; //often set to -1 in the AppModel to make -1 the default
$this->find('all', array(
'conditions' => array(
'Page.id' => $id
),
'contain' => array(
'Comment' => array(
'User' => array(
'Profile',
),
),
)
));
}
这篇关于CakePHP - 如何检索深层关联的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!