gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:00:44 25 4
gpt4 key购买 nike

我有两个表“机构”和“代理”,我想使用计数查询显示每个机构拥有的代理数量(“代理”表有一列名为“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com