我有两个表“机构”和“代理”,我想使用计数查询显示每个机构拥有的代理数量(“代理”表有一列名为“agency_id”)。有一个old post在 stackoverflow 上,但还没有完全回答。
这是我迄今为止尝试过的:
在机构模型中(获取机构 GridView 中的代理数量):
*/
public function getAgents()
{
return $this->hasMany(Professionnels::className(), ['agency_id' => 'id']);
}
在代理模型中(在代理 GridView 中获取代理名称):
public function getAgencies()
{
return $this->hasOne(Agencies::className(), ['id' => 'agency_id']);
}
在显示 GridView 的机构 View 中:
'columns' => [
....,
['label' => 'Agents Number','attribute' => 'count(agents.id'),]
在机构搜索中:
$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',
]
关于mysql - Yii2 - 使用 activerecord 在 gridview 中显示关系数据的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588242/