Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two tables and get values in Yii2 gridview

I'm using Yii2 gridview widget to display the data.

I'm using two tables named as message and message_trigger.

In message table columns are object_model, Object_id.

In message_trigger the column are object_id, object_name.

The grid get the values from the table message. So grid fields are Object_model, Object_id.

Now my problem is I need to show Object_name from the table message_trigger based on the object_id from the table message.

In my form I have used grid like this

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

In model I have used

public function search($params){
    $query = AlertTrigger::find()->where(['alert_id'=>$params['id']])->andWhere(['!=','status',2]);
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
}
like image 468
JeevaRekha Avatar asked Aug 23 '15 11:08

JeevaRekha


2 Answers

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} '],
    ],
]); ?>
like image 65
ankitr Avatar answered Nov 17 '22 03:11

ankitr


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.

like image 4
Mahendran Sakkarai Avatar answered Nov 17 '22 05:11

Mahendran Sakkarai