【问题标题】:Yii strange behavior: CGridView + group + withYii 奇怪行为:CGridView + group + with
【发布时间】:2012-06-15 02:51:33
【问题描述】:

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

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

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

为此,我将group 添加到标准中,效果很好。

但如果我想按任何相关字段过滤视图,我必须将with 添加到条件中,它适用于过滤或搜索,但结果的总显示不正确显示 正在显示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';

【问题讨论】:

  • 我遇到了类似的问题,只是反过来。 CGridView 显示的结果比寻呼机少,我最终设置了一个非常大的限制。最终这可能是一个Yii 错误

标签: php mysql gridview yii


【解决方案1】:

我在 yii 的论坛上找到了它,由一个名为“bennouna”的用户发布。 它对我有用。

public function groupedSearch() {
  $criteria = new CDbCriteria;
  $criteria->select = '…';
  $criteria->with = array(…);
  $criteria->group = '…';
  $dp = new CActiveDataProvider($this, array('criteria'=>$criteria));
  $dp->setTotalItemCount(count($this->findAll($criteria)));
  return $dp;
}

【讨论】:

    【解决方案2】:

    当使用 CActiveDataprovider 时,YII 不使用标准中建立的“with”来执行“totalItemCount”,因此它会显示不带 with 的结果总数。我建议您手动添加连接条件来克服这个问题:)

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

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

    【讨论】:

    • 但是我想用 `reports_count' 显示的是特定用户在数据库中的总行数。比如我的数据库有15个用户:user1被举报了14次,user2被举报了1次。
    • 我找到了方法,我将用解决方案更新我的问题。
    • 你的解决方案很棒。很高兴你得到答案:)
    猜你喜欢
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2012-12-11
    • 1970-01-01
    • 2012-11-01
    • 2019-11-28
    • 2013-11-12
    相关资源
    最近更新 更多