Find conditions with hasMany model

[亡魂溺海] 提交于 2019-11-28 10:23:27

You need call the containableBehaivor on your model

<?php
class Item extends AppModel {
    public $actsAs = array('Containable');
}

in your controller you can make the query

$items = $this->Item->find('all', array(
           'contain'=>array(
                 'ItemDetail',                                                                
                 'Category'=>array(
                       'conditions'=>array('Category.item_category_id'=>1)
                  ),
                 'Favorite'=>array(
                       'conditions'=>array('Favorite.member_id'=>8)
                  )
              )
          );
$this->set('test', $items);

try using Joins

$items = $this->Item->find('all', array(
            'joins' => array( 
                        array( 
                            'table' => 'categories', 
                            'alias' => 'Category', 
                            'type' => 'inner',  
                            'conditions'=> array('Category.item_category_id' => 1) 
                        ), 
                        array( 
                            'table' => 'favorites', 
                            'alias' => 'Favorite', 
                            'type' => 'inner',  
                            'conditions'=> array('Favorite.member_id' => 8, 'Item.id = Favorite.item_id') 
                            )
                        ),
           'contain'=>array('ItemDetail','Category','Favorite')
          );
$this->set('test', $items);

You could also try something like this:

$this->Item->hasMany['Favorite']['conditions']['member_id'] = 8;

Which has the same effect as rebinding the model with the condition.

Just a possible issue. The above will add the condition for the rest of the request, if you want to rollback to the previous behavior, you need to unset the condition:

unset($this->Item->hasMany['Favorite']['conditions']['member_id']);

Remember to set the $this->Item->recursive property to the desired value (recursive attribute). The default it's 1, which it's the minimum you need for this to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!