我想再问你一个关于CakePHP的问题:我有2个模型用户和评论与关系1-n(一个用户有许多评论)。我想使用find()列出信息用户和它的注释格式数据返回:
Array
(
[User] => Array
(
[id] => 121
[name] => Gwoo the Kungwoo
[created] => 2007-05-01 10:31:01
)
[Comment] => Array
(
[0] => Array
(
[id] => 123
[user_id] => 121
[title] => On Gwoo the Kungwoo
[body] => The Kungwooness is not so Gwooish
[created] => 2006-05-01 10:31:01
)
[1] => Array
(
[id] => 124
[user_id] => 121
[title] => More on Gwoo
[body] => But what of the 'Nut?
[created] => 2006-05-01 10:41:01
)
)
)
但我不想配置关系hasMany在模型用户为例链接:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html。我试过这个代码:
$data = $this->User->find('all', array(
'joins' => array(
array(
'table' => 'comment',
'alias' => 'Comment',
'type' => 'LEFT',
'conditions' => array(
'User.id = Comment.user_id'
)
),
'conditions' => array(
'User.id' => $userId
),
'fields' => array('User.*', 'Comment.*')
));
Cake返回一个包含用户重复记录的数组(例如:如果用户有2条评论,它返回用户重复的2条记录)
谁能给我另一个解决方案吗?(但除了解决方案配置有许多关系模型),谢谢。或者你可以在你的控制器中使用bindModel
$this->User->bindModel(
array(
'hasMany'=>array(
'Comment' =>array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'conditions' => array('Comment.status' => 'Active'),
)
)
)
);
$data = $this->User->find('all',array('conditions'=>array('User.email'=>$userEmail)));
查看更多信息
看看这个答案的一些信息,通过这个链接查看绑定和解绑定模型的详细信息