Yii2 GridView排序计数(*)从另一个表


Yii2 GridView sorting by count(*) from another table

我的应用程序有这些表:

  • 文章(包括category_id列对category(id)的引用)

输出gridview

<?=
  GridView::widget([
    ...
    'columns' => [
       ...
        [
            'label' => 'Article count',
            'attribute' => 'articles',
            'value' => function ($model, $key, $index, $column) {
                return count($model->articles);
            },
        ],
        ...
    ],
  ])
?>

我想按文章排序。我该怎么做呢?

首先,不要直接在视图中获取count值,而是从Model谁是admin谁在排序

$criteria = new CdbCriteria();

为csort()提供Model中的count变量像

$sort = new CSort();
$sort->defaultOrder = 'id DESC';
$sort->attributes = array(
                                'articles'=>array(
                                    'asc'=>'c.articles ASC',
                                    'desc'=>'c.articles DESC',
                                ),
                                '*',
    );

然后提供$sort变量给ActiveDataProvider

return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'sort' => $sort,
    ));