How to join two tables and get values in Yii2 gridview

风流意气都作罢 提交于 2019-12-03 13:05:14

In Message Model

public function getMessageTrigger()
{
    return $this->hasOne(MessageTrigger::className(), ['object_id' => 'object_id']);
}

in view

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'object_model',
        'object_id',
        [
            'label' => 'Name',
            'value' => 'messageTrigger.object_name',
        ],
        ['class' => 'yii\grid\ActionColumn', 'template' => '{view} {update} {delete} '],
    ],
]); ?>
Mahendran Sakkarai

ankitraturi answer is the best answer. If anybody want to get value using a function from the model and use it in the gridview means follow the below steps.

  1. Add the function which returning the value in the a model(Here I use Message Model).
public static function get_message_trigger($id){
    $model = MessageTrigger::find()->where(["object_id" => $id])->one();
    if(!empty($model)){
        return $model->object_name;
    }

    return null;
}
  1. In the Gridview use like below.
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'object_model',
        'object_id',
        [
            'label' => 'Name',
            'value' => function($data){
                return Message::get_message_trigger($data->object_id)
            },
        ],
        ['class' => 'yii\grid\ActionColumn', 'template' => '{view} {update} {delete} '],
    ],
]); ?>

Hope this will help someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!