php - Yii 奇怪的行为 : CGridView + group + with

标签 php mysql gridview yii

我有一个奇怪的行为,我将尝试解释。

我正在构建一个报告系统,每个用户都可以让其他用户报告他们的个人资料、图片或消息。

在后端我想显示一个 CGridView每个用户出现在一行中,并报告了总次数。

为此,我将 group 添加到条件中,效果很好。

但如果我想按任何相关字段过滤 View ,我必须将 with 添加到条件中,它适用于过滤或搜索,但结果的总显示不正确显示 Displaying 1-2 of 15 result(s) 当它应该显示 Displaying 1-2 of 2 result(s) 在报告表中我有 15 行但只有两个用户,还添加了一个不存在的分页。

模型/Report.php

public function relations()
{
    return array(
        'reported' => array(self::BELONGS_TO, 'User', 'reported_id'),
    );
}

public function search()
{
    $criteria = new CDbCriteria();
    $criteria->select = array(
        '*',
        'count(*) as reports_count',
    );
    $criteria->group = 't.reported_id';
    $criteria->with = array('reported');

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria,
        'sort'=>array(
            'attributes'=>array(
                'status_search'=>array(
                    'asc'=>'reported.user_status_id',
                    'desc'=>'reported.user_status_id DESC',
                ),
                'reports_count' => array(
                    'asc' => 'reports_count ASC',
                    'desc' => 'reports_count DESC',
                ),
                '*',
            ),
        ),
        ));
} 

更新:我找到了使用 join 而不是 with 并选择我需要的字段而不是使用 * 选择所有字段的解决方案:

$criteria->select = array(
        't.id, t.reported_id',
        'count(*) as reports_count',
    );
$criteria->group = 't.reported_id';
$criteria->join = 'LEFT JOIN user u on u.id = t.reported_id';

最佳答案

当使用 CActiveDataprovider 时,YII 不使用条件中建立的“with”来执行“totalItemCount”,所以它会说没有 with 的结果总数。我建议您手动添加连接条件来克服这个问题:)

$criteria->join = 'left join User u on u.id=t.reported_id'

并删除 $criteria->select 并使用 CActiveDataProvider 的 'totalItemCount' 方法。

关于php - Yii 奇怪的行为 : CGridView + group + with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10992997/

相关文章:

php - OpenCart 是否对 OWASP 前 10 强?

php - 按时间戳排序已损坏?

android - 如何强制 GridView 加载单元格

android - 如何在 Android 的 GridView 中使用预加载器

asp.net - IListSource 不包含任何数据源

php - 如何从文件名中删除目录字符串

php - Laravel voyager - 需求无法解决

php - SQLSTATE[23000] : Integrity constraint violation: 1048 Column 'property_id' cannot be null in Laravel 5. 2

php - MySqli更新查询中的随机数

php - 列出数据库中的所有用户,多列和升序