The task is to link 2 tables.

The table of users and comments, it is necessary that the user’s name be displayed not by the user’s ID

GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'content:ntext', 'page_id', 'created', 'user_id' => [ 'attribute' => 'user_id', **'value' => 'user_id'**, //пытался сделать так 'value'=> app\modules\admin\controllers\CommentController::getID('user_id') ], // 'guest', \app\models\Users::getUsers(user_id) ['class' => 'yii\grid\ActionColumn'], ], ]); 

The key should have chosen the user, but, he says, he does not know the app\modules\admin\controllers\CommentController::getID('user_id') .

    2 answers 2

    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'], ], ]); 

      This problem was solved by creating a view for both tables in mysql and then creating a model for this view.