YII CActiveDataProvider with relational tables

后端 未结 2 1329
灰色年华
灰色年华 2021-01-14 00:24

I have three tables:

  • Content (id)
  • ContentCategory (id_content, id_category)
  • Category (id)

Relations of Content,



        
相关标签:
2条回答
  • 2021-01-14 00:33

    Relational Query with through

    0 讨论(0)
  • 2021-01-14 00:44

    When tables are related MANY_MANY or HAS_MANY, Yii can sometimes break a single query into two SQL statements. I believe this is for efficiency, but it can mess up something like you are trying to do, since the Categories query is happening in a different SQL statement than the Contact query.

    The solution is to use a lesser-known property of CDbCriteria called together. If you set this to true, it will force the query to select from both tables in the same SQL statement. The condition you have will then be effective.

    If you always want this to happen, add it to the relation:

    Categories' => array(self::MANY_MANY, 'Category', 'ContentCategory(id_content, id_category)','together'=>true),
    

    If you want it just in the $dataProvider case above, add it to the parameters like this:

    'criteria'=>array(
       'with'=>array(
           'Categories'=>array(
                'condition'=>'id_category=1'
            ),
        ),
        'together'=>true,
    ),
    
    0 讨论(0)
提交回复
热议问题