简体   繁体   中英

CakePHP HABTM condition

I want to make a condition on my HABTM attributes I have the following HABTM relations in CakePHP 2.x:

Practise.php

public $hasAndBelongsToMany = array(
    'Attribute' => array(
        'className' => 'Attribute',
        'joinTable' => 'practises_attributes',
        'foreignKey' => 'practise_id',
        'associationForeignKey' => 'attribute_id',
        'unique' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
    )
);

Attribute.php

public $hasAndBelongsToMany = array(
    'Practise' => array(
        'className' => 'Practise',
        'joinTable' => 'practises_attributes',
        'foreignKey' => 'attribute_id',
        'associationForeignKey' => 'practise_id',
        'unique' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
    )
);

Now I want to find all including a condition on Attributes in my PractiseController.php

PractiseController.php

$cond['Attribute.id'] = array(1,2,3);
$this->Practise->find('all', array('conditions' => $cond));

Then I get the following error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attribute.id' in 'where clause'

SQL Query:

SELECT Practise . id , Practise . title , Practise . body , FROM db . practises AS Practise WHERE Attribute . id IN (1, 2, 3)

How can I make CakePHP also Join the HABTM table into the find query?

You can use contain for example

$this->Practise->find('all', array('contain' => 'Attribute.id = whatever'));

You can manually join too with:

 $options['joins'] = array( array('table' => 'practises_attributes', 'alias' => 'PractiseAttribute', 'type' => 'INNER', 'conditions' => array( 'Attribute.id = whatever', ) ) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM