CakePHP HABTM条件

时间:2014-12-14 12:22:44

标签: php mysql cakephp has-and-belongs-to-many

我想对我的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表加入查找查询?

1 个答案:

答案 0 :(得分:0)

您可以使用包含例如

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