Option with a minimum of additional code and maximum use of the capabilities of Yii2 .
First of all, explicitly defined relations between the Comment and User models are necessary (it would be more correct to use a single number when naming the models). Yii2 itself adds the necessary methods to the model when generating code using Gii , so there should be such methods:
// app\models\Comment public function getUser() { return $this->hasOne(User::className(), ['id' => 'id_user']); } // app\models\User public function getComments() { return $this->hasMany(Comment::className(), ['id_user' => 'id']); }
If not, you can add manually. These two methods will allow you to make a bunch of models in the CommentSearch class, the procurement of which is again generated by Gii . In the search () method, we change:
// app\models\CommentSearch $query = Comment::find();
on:
// app\models\CommentSearch $query = Comment::find()->with('user');
Transferring data from the model to the controller (in the default controller, you don’t even need to change anything):
// app\controllers\CommentsController public function actionIndex() { $searchModel = new CommentSearch(); $dataProvider' = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); }
And display the data using the GridView:
GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //... 'user.name', //... ['class' => 'yii\grid\ActionColumn'], ], ]);