开发者

CakePHP: conditions with hasMany

I have a Blog model that has defined var $hasMany=array("Comment");

How can i apply a filter on the Comments to select only the Blog items that match a certain Comment category?

If, in the Blog model, i do

$this->recursive=2;
$this->hasMany=array("Comment");  //in Comment i have $belongsTo("B开发者_高级运维log")
return $this->find("all",array("conditions"=>array("Comment.comment_type_id"=>123)));

i get an error that says Unknown Comment.comment_type_id column because Cake does not make the join.

I think this is a rather common issue so i believe simple to solve but i can't find a good way


 $this->bindModel(array(
    'hasMany' => array(
        'Comment' => array(
            'conditions' => array('Comment.comment_type_id' => 123)
         ))));
$this->find('all');

or if the Model is already binded with comment use :

$this->hasMany['Comment']['conditions'] = array('Comment.comment_type_id' => 123);
$this->find('all');


You could work in reverse and select all comments in a particular category and include the blog posts that they were posted to. I can't find it at the moment, but I'm pretty sure I've seen that in the docs as the "recommended" approach and it might be perfectly sufficient in this relatively simple case. It's definitely what I'd try first.

You could also use the containable behavior and set a condition on including the Comment, but that will return all blog posts and and no comments where the comment category doesn't match what you're after. I've never liked this solution because it just feels clumsy and inaccurate to me (though it's technically not).

If I really want to limit things, I often use ad hoc joins. I like that they keep my results as clean as possible even though it makes for a more verbose find array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜