我想对我的HABTM属性做一个条件
我在CakePHP 2.x中具有以下HABTM关系:

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' => '',
    )
);


现在,我想在我的PractiseController.php中找到所有包含属性条件的条件

PractiseController.php

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


然后我得到以下错误:

错误:SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ Attribute.id”

SQL查询:

选择
        Practiseid
        Practisetitle
        Practisebody
    从dbpractises AS Practise
    在Attributeid IN(1、2、3)中

如何使CakePHP也可以将HABTM表加入查找查询中?

最佳答案

您可以使用包含为例

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


您也可以手动加入:



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

07-27 19:31