使用控制器中的自定义条件检索所有记录

时间:2014-05-16 16:11:41

标签: cakephp cakephp-2.3

我有一个简单的问题,但我坚持了!

我有2个型号。项目和类型学。

类型属于项目 项目HasMany类型。

表格就像这样。

TYPOLOGY: id | item_id | title | description | published

ITEM:     id | title | price | created | published

所以我想要retreava是。 要查找所有类型的WHERE已发布= 1和它们已发布的项目= 1。

在TypologyControllers中,我写了这段代码:

$typologies = $this->Typology->find(
'all', 
array(
'contain' => array(
'Item' => array(
'conditions' => array(
'Item.published =' => "1"))), 
'conditions' => array(
'Typology.published'=>'1'), 
'recursive' => -1, 
'order' => array(
'Typology.' . $this->Typology->primaryKey . ' DESC')
));



    $this->set('typologies', $typologies);  

1 个答案:

答案 0 :(得分:1)

为什么你不使用连接:

$typologies = $this->Typology->find('all', array(
         'joins' => array(
            array(
                'table' => 'items',
                'alias' => 'Item',
                'type' => 'LEFT',
                'conditions' => array(
                'Item.id = Typology.item_id'
                )
            )
        ),
            'conditions' => array(
            'Item.published' => 1, 
            'Typology.published' => 1 
        ),
            'order' => array(
            'Typology.id' => 'DESC'
        ),
            'fields' => array('Item.*', 'Typology.*'),
            'recursive' => -1
        ));


    $this->set('typologies', $typologies);