[英]Yii2 - show count of relation data in gridview using activerecord
I have two tables Agencies and Agents, I want to show the number of agents each agency has using a count query ("agents" table has a column called 'agency_id'). 我有两个表Agencies和Agents,我想使用计数查询显示每个代理商的代理商数量(“ agents”表格的列名为“ agency_id”)。 there is an old post here on stackoverflow but it's not completely answered.
这里有一个关于stackoverflow的旧帖子 ,但尚未完全回答。
Here's what I tried so far: 这是我到目前为止尝试过的:
In Agencies Model (to get the agent count in agencies gridview): 在代理商模型中(以在代理商gridview中获得代理商计数):
*/
public function getAgents()
{
return $this->hasMany(Professionnels::className(), ['agency_id' => 'id']);
}
In Agents Model (to get the agency name in agents gridview): 在“代理商模型”中(要在代理商gridview中获得代理商名称):
public function getAgencies()
{
return $this->hasOne(Agencies::className(), ['id' => 'agency_id']);
}
In Agencies view that shows the gridview: 在显示网格视图的“代理”视图中:
'columns' => [
....,
['label' => 'Agents Number','attribute' => 'count(agents.id'),]
And in the AgenciesSearch: 在AgenciesSearch中:
$query = Agencies::find()->with('agents');
You can call the count()
function on your relationship in the value
attribute of your column: 您可以在关系的列的
value
属性中调用count()
函数:
'columns' => [
....,
[
'label' => 'Agents Number',
'attribute' => 'agents',
'value' => function ($model) { return $model->getAgents()->count();}
]
Another option would be to create a new method to get the Agents count in your Agency model: 另一种选择是创建一种新方法来使代理商模型中的代理商计数:
public function getAgentsCount()
{
return $this->getAgents()->count();
}
And call refer to it in your column: 并在您的列中调用引用它:
'columns' => [
....,
[
'label' => 'Agents Number',
'attribute' => 'agentsCount',
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.