CakePHP - 在模型中查找没有 hasMany 关系的 hasMany 关联?
CakePHP - Find hasMany association without hasMany relation in Model?
我想再次问你一个关于 CakePHP 的问题:我有 2 个模型用户和评论,关系为 1-n(一个用户有很多评论)。我想使用 find() 列出用户及其评论的信息,格式数据为 return :
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 作为 link 中的示例: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 return 一个包含用户重复记录的数组(例如:如果用户有 2 条评论,则 return 有 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)));
更多info
已更新
看看这个answer for some info, see details about bind and unbind model through this link
我想再次问你一个关于 CakePHP 的问题:我有 2 个模型用户和评论,关系为 1-n(一个用户有很多评论)。我想使用 find() 列出用户及其评论的信息,格式数据为 return :
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 作为 link 中的示例: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 return 一个包含用户重复记录的数组(例如:如果用户有 2 条评论,则 return 有 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)));
更多info
已更新
看看这个answer for some info, see details about bind and unbind model through this link