0

We have the Ebooks HABTM Tags. And we try to select the Ebooks that have belong to the tag with id=160.

Both use the containable behavior, so in the Ebooks Controller I have written the following:

$this->Ebook->contain('Tag.id = "160"');
$ebooks = $this->Ebook->find('all');

According the book this should return the needed result. Instead of that, a list of all ebooks is given back.

Note also that two queries are run, the first returns the list of all Ebooks and the second the ebooks that should be returned. Does anyone have any idea?

Thanks in advance

Dimitris S.
  • 115
  • 7

1 Answers1

2

Yes, this query says "Find all Ebooks and include with them all Tags with the id 160".
contain does not limit the primary result, only the related results.

You need to make an SQL JOIN to the HATBM table and filter your primary results on it, like so:

$this->Ebook->bindModel(array('hasOne' => array('EbooksTag')));
$this->Ebook->find('all', array(
    'conditions' => array('EbooksTag.tag_id' => 160)
));
deceze
  • 510,633
  • 85
  • 743
  • 889
  • could this be used as a MUCH simpler way to solve my question [here](http://stackoverflow.com/questions/5655977/cakephp-problem-with-habtm-paginate-query)? – Dave Apr 26 '11 at 01:15
  • @Dave HABTM relationships are tricky to query. The rule to keep in mind is that Cake will automatically create JOINs for belongsTo and hasOne relationships in the "primary" query (the one containing the condition), while hasMany and HABTM relations will be queried separately (by necessity, because they return more than one row). Sometimes it's easier to specify `joins` explicitly, sometimes it's easier to bind models, sometimes it's easier to query *from the other model*. Keep playing around with it. :) – deceze Apr 26 '11 at 01:23