2
votes

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("Blog")
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

2

2 Answers

8
votes
 $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');
2
votes

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.