在cakephp中是否有一种方法可以使用ORM来获取属于特定子项的项目。例如,我要获取特定评论记录的相关Post记录。
这是我的评论模型:
var $belongsTo = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'post_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
我正在尝试这个,但它会撤回每个帖子,即使那些没有我要查询的评论:
$this->Post->contain('Comment');
$results = $this->Post->find('all', array(
'contain' => array(
'Comment' => array(
'conditions' => array(
'id' => 15
)
)
)));
还有其他方法吗?
答案 0 :(得分:0)
您确定不必在条件中指定模型吗?
例如:
$this->Post->contain('Comment');
$results = $this->Post->find('all', array(
'contain' => array(
'Comment' => array(
'conditions' => array(
'Comment.id' => 15
)
)
)));
答案 1 :(得分:0)
我的研究让我发表了关于这个问题的帖子包含: http://nuts-and-bolts-of-cakephp.com/2008/07/17/forcing-an-sql-join-in-cakephp/
所以我的最终解决方案如下:
$this->Post->unbindModel(array('hasMany' => array('Comment')));
$results = $this->Post->bindModel(array('hasOne' => array(
'Comment' => array(
'foreignKey' => false,
'conditions' => array('Comment.post_id = Post.id'))
)));
$results = $this->Post->find('all', array(
'conditions' => array(
'Comment.id' => 10
)));
不漂亮,但完成工作:)