2017-04-24 35 views
0

我有兩個表代理和代理,我想顯示每個代理使用計數查詢的代理數(「代理」表有一個名爲'agency_id'的列) 。這裏有一個old post在stackoverflow,但它沒有完全回答。Yii2 - 使用主動記錄顯示gridview中關係數據的計數

這裏是我試過到目前爲止:

在代理模型(以獲得代理機構的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:

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

而在AgenciesSearch:

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

回答

2

可以調用count()功能,您在您的專欄的value屬性關係:

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

另一種選擇是創建一個新的方法來獲得代理商在您的代理商型號中計算:

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

A nd電話請參閱您的專欄:

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

它作爲魅力。我仍然必須定義排序和filtring,但感謝你的男人 –

相關問題