Search code examples
phpgridviewyii2dataprovider

Q: yii2 dataProvider doesn't display join attributes


I have a relation between User and Thesis and my dataProvider just displays user attributes and not thesis'ones in the Gridview. Is there a better way to print join attributes than: ['attribute'] => ['table.attribute']?

model:

public function search($params)
{
    $query = Request::find()->joinWith('user')->joinWith('thesis')->where(['thesis.staff'=> Yii::$app->user->identity->id]);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

view:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        //'id',
        'title',
        ['attribute' => 'thesis',
        'value' => 'thesis.title'],
        //'company',
        'description:ntext',
        'duration',
        ['attribute' => 'user'
        'value' => 'user.id'],
        //'requirements',
        //'course',
        'n_person',
        'ref_person',
        'is_visible:boolean',
        //'created_at',
        //'staff',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

controller:

public function actionIndex()
{
    $searchModel = new SearchRequest();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

Solution

  • You need to add the relation getters on your model.

    On your Thesis model, you need to add something like

    public function getUser0 () {
        return $this->hasOne(\your\user\model\location\User::className(), ['id' => 'user']);
    }
    

    Having this on your model will populate via lazy-load the user relation when you call Thesis::user0, in your case, something like this:

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            /// ---- other attributes
            ['attribute' => 'user0.name'],
            /// ---- other attributes
        ],
    ]); ?>