Dear Friend
Here is one implementation.
1.Make a public property commentCount in Post model and make it safe on search.
public $commentCount;
array('commentCount', 'safe', 'on'=>'search'),
Post::search
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->with="comments";
$criteria->together=true;
$criteria->select="t.*,(SELECT COUNT(tbl_comment.id) FROM tbl_comment WHERE t.id=tbl_comment.post_id) AS commentCount";
$criteria->group="t.id";
$criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('content',$this->content,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('status',$this->status);
$criteria->compare('create_time',$this->create_time);
$criteria->compare('update_time',$this->update_time);
$criteria->compare('author_id',$this->author_id);
$criteria->compare('(SELECT COUNT(tbl_comment.id) FROM tbl_comment WHERE t.id=tbl_comment.post_id)',$this->commentCount);//making the filters work
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>4),
'sort'=>array('attributes'=>array('commentCount'=>array(),'*')),
));
}
Now in admin.php add the commentCount as a column.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'content',
'create_time',
'update_time',
'commentCount' //commentCount added as a column.
..............................................................
If you have created any default scopes involving sorting post table, you have to remove it.
Regards.