Yii2 - 使用 activerecord 在 gridview 中显示关系数据的计数

Yii2 - show count of relation data in gridview using activerecord

我有两个 tables Agencies 和 Agencies,我想使用计数查询显示每个机构拥有的代理数量("agents" table 有一个名为 'agency_id'). Whosebug 上有一个 old post,但没有完全回答。

这是我到目前为止尝试过的方法:

在代理模型中(在代理网格视图中获取代理计数):

 */
public function getAgents()
{
    return $this->hasMany(Professionnels::className(), ['agency_id' => 'id']);

}

在代理模型中(在代理网格视图中获取代理名称):

public function getAgencies()
{
    return $this->hasOne(Agencies::className(), ['id' => 'agency_id']);
}

在显示网格视图的机构视图中:

'columns' => [
        ....,
         ['label' => 'Agents Number','attribute' => 'count(agents.id'),]

在 AgenciesSearch 中:

$query = Agencies::find()->with('agents');

您可以在列的 value 属性中对您的关系调用 count() 函数:

'columns' => [
....,
  [
    'label' => 'Agents Number',
    'attribute' => 'agents',
    'value' => function ($model) { return $model->getAgents()->count();}
  ]

另一种选择是创建一种新方法来获取代理模型中的代理数:

public function getAgentsCount()
{
    return $this->getAgents()->count();
}

并在您的专栏中引用它:

'columns' => [
    ....,
      [
        'label' => 'Agents Number',
        'attribute' => 'agentsCount',
      ]