我有两个表格,例如Customer(id,f_name,l_name)
和cycle (id,customer_id,cycle_name,address)
。
我使用客户控制器作为base -grid; 我想在yii2中的网格视图中显示cyclename。
答案 0 :(得分:2)
在Customer
模型放置关系中(但我现在不使用hasOne
或hasMany
,我将使用haOne
)):
public function getCycle()
{
return $this->hasOne(Cycle::className(), ['customer_id' => 'id']);
}
在控制器中:
public function actionGrid(){
$query = Customer::find()->with(['cycle']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $this->render('grid', [
'dataProvider' => $dataProvider,
]);
}
从查看使用:
<?= \yii\grid\GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'f_name',
[
'label' => 'Cycle',
'value' => function ($data) {
return $data->cycle->cycle_name;
}
]
]
]); ?>