Find conditions with hasMany model

前端 未结 2 1026
梦如初夏
梦如初夏 2020-12-10 08:12

I have 4 model:

Item------hasMany---->Detail

Item------hasMany---->Favourite

Item------hasMany---->Category

How can I find all Item that has

相关标签:
2条回答
  • 2020-12-10 08:53

    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);
    
    0 讨论(0)
  • 2020-12-10 09:04

    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.

    0 讨论(0)
提交回复
热议问题