如何在yii2.0中搜索网格中多个表的数据

时间:2015-02-17 05:03:43

标签: grid yii2 show

我有两个表格,例如Customer(id,f_name,l_name)cycle (id,customer_id,cycle_name,address)

我使用客户控制器作为base -grid; 我想在yii2中的网格视图中显示cyclename。

1 个答案:

答案 0 :(得分:2)

Customer模型放置关系中(但我现在不使用hasOnehasMany,我将使用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; 
                }
            ]
        ]
    ]); ?>