带有关系表的 YII CActiveDataProvider [英] YII CActiveDataProvider with relational tables

查看:33
本文介绍了带有关系表的 YII CActiveDataProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三张桌子:

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

内容关系,

'Categories' => array(self::MANY_MANY, 'Category', 'ContentCategory(id_content, id_category)'),
'category' => array(self::HAS_MANY, 'Category', 'id'),

我需要获取具有特定类别的所有内容记录(在 CActiveDataProvider 中以在 CListView 中使用).

I need to fetch all the records of Content that have some specific Category (in a CActiveDataProvider to use in CListView).

当我使用 findAll() 时,我得到了我想要的记录(它有效),

When I use the findAll(), I get the records I want (it works),

$model=Content::model()->with(array(
'Categorieses'=>array(
    'condition'=>'id_category=1',
),
))->findAll();

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

But when I do with CActiveDataProvider I get all the records in Content (not the ones that have specific Category - Not works)

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

我该怎么做?

非常感谢!

推荐答案

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

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.

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

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),

如果你只是在上面的 $dataProvider 情况下想要它,请将其添加到参数中,如下所示:

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,
),

这篇关于带有关系表的 YII CActiveDataProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆