How do I query data in CakePHP using HABTM relationships?

会有一股神秘感。 提交于 2019-12-04 06:14:13
neilcrookes

Turn your debug level up to 2 and look at the SQL output. Find the query that your code is generating and you'll notice there are several. The ORM layer in CakePHP doesn't join HABTM related tables in the first query. It gets the results from the first select, then separately fetches the HABTM data for each item. Because the join table is not in the first query, your condition, which is intended for use on a joined table, results in the error you are seeing.

The cook book has a section on HABTM associations and fetching data based on conditions in the HABTM table that will fit your requirements.

Asif Zardari

From the Cookbook: http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM

One option is to search the Tag model (instead of Recipe), which will also give us all of the associated Recipes.

$this->Recipe->Tag->find('all', array(
    'conditions' => array('Tag.name' => 'Dessert')));

We could also use the join table model (which CakePHP provides for us), to search for a given ID.

$this->Recipe->bindModel(array('hasOne' => array('RecipesTag')));
$this->Recipe->find('all', array(
    'fields' => array('Recipe.*'),
    'conditions' => array('RecipesTag.tag_id' => 124) // id of Dessert
));

It's also possible to create an exotic association for the purpose of creating as many joins as necessary to allow filtering, for example:

$this->Recipe->bindModel(array('hasOne' => array('RecipesTag',
    'FilterTag' => array(
        'className' => 'Tag',
        'foreignKey' => false,
        'conditions' => array('FilterTag.id = RecipesTag.tag_id')
))));
$this->Recipe->find('all', array(
    'fields' => array('Recipe.*'),
    'conditions' => array('FilterTag.name' => 'Dessert')
));

Your table should be called "schools_users" and not "school_members" because it's many-to-many, thus using the plural form in the table name on both sides is appropiate.

You also set the Model ClassName "School" as Alias for the HABTM. You should change that to something more generic like "Schools" as in "User is in and has many SchoolS" to avoid conflicts.

And another hint: Try to find the user "via" the School Model rather than the User Model.

$this->User->Schools->find()

Hope this helps.

FWIW, your join tables do appear to be "oddly named" insofar as they don't follow the convention described here:

http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM

In any case, good luck, I remember HABTM being a butt-pain in CakePHP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!