Yii weird behavior: CGridView + group + with

I have strange behavior that I will try to explain.

I am creating a reporting system in which each user can have his own profile, images or messages communicated by other users.

In the backend, I want to show a CGridView where each user is reported in a row with a total number of times.

To do this, I add group to the criteria and it works well.

But if I want to filter the view by any related field, I have to add with criteria, and it works well with filtering or searching, but the general display of the results is incorrect, showing Display 1-2 of 15 results , when it should display Display 1-2 of 2 results , as in the report table. I have 15 lines, but only two users, adding also non-existent pagination.

Models / 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', ), '*', ), ), )); } 

Update: I found a solution using the connection instead of using and to select the fields I need, rather than selecting all of them 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'; 
+4
source share
2 answers

When using CActiveDataprovider, YII does not use the 'with' parameter set in the criteria for executing 'totalItemCount', so it will show the total number of results without. I recommend that you manually add join conditions to overcome this :)

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

And remove the criterion $ criteria-> and use the totalItemCount method for CActiveDataProvider.

+4
source

I found it on the yii forum posted by a user named "bennouna". That helped.

 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; } 
+3
source

All Articles