doubanduo7620 2014-12-14 12:22
浏览 17

CakePHP HABTM条件

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?

  • 写回答

1条回答 默认 最新

  • duanjue9296 2014-12-14 22:23
    关注

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

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制