YII CActiveDataProvider与关系表

Cal*_*ete 4 yii

我有三张桌子:

  • 内容(id)
  • ContentCategory(id_content,id_category)
  • 类别(id)

内容关系,

'Categories' => array(self::MANY_MANY, 'Category', 'ContentCategory(id_content, id_category)'),
'category' => array(self::HAS_MANY, 'Category', 'id'),
Run Code Online (Sandbox Code Playgroud)

我需要获取具有某些特定类别的内容的所有记录(在CAistDataProvider中用于CListView).

当我使用findAll()时,我得到了我想要的记录(它的工作原理),

$model=Content::model()->with(array(
'Categorieses'=>array(
    'condition'=>'id_category=1',
),
))->findAll();
Run Code Online (Sandbox Code Playgroud)

但是当我使用CActiveDataProvider时,我获得了Content中的所有记录(不是那些具有特定类别的记录 - 不起作用)

$dataProvider=new CActiveDataProvider('Content',
        array(
                'pagination'=>array('pageSize'=>15),
                'criteria'=>array(
                    'with'=>array(
                        'Categories'=>array(
                            'condition'=>'id_category=1',
                        ),
                    ),
                ),
            )
        );
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

非常感谢!

小智 13

当表与MANY_MANY或HAS_MANY相关时,Yii有时可以将单个查询分成两个SQL语句.我相信这是为了提高效率,但它可能会像你试图做的那样搞乱,因为Categories查询发生在与Contact查询不同的SQL语句中.

解决方案是使用一个鲜为人知的CDbCriteria被调用属性together.如果将其设置为true,则会强制查询从同一SQL语句中的两个表中进行选择.你的条件将有效.

如果您总是希望这样,请将其添加到关系中:

Categories' => array(self::MANY_MANY, 'Category', 'ContentCategory(id_content, id_category)','together'=>true),
Run Code Online (Sandbox Code Playgroud)

如果你只想在$dataProvider上面的情况下,将它添加到这样的参数:

'criteria'=>array(
   'with'=>array(
       'Categories'=>array(
            'condition'=>'id_category=1'
        ),
    ),
    'together'=>true,
),
Run Code Online (Sandbox Code Playgroud)