Skip to content
Advertisement

Get parent name of a user GridView Yii2

I want to get the parent username of a user

The ‘parent.username’ works this way:

But I need url the user profile, and I have it like this

[

'attribute' => 'parent_id',
 'value' => function(User $model) {
 return Html::a(Html::encode($model->parent_id ? $model->parent_id : " "), ['view', 'id' => $model->parent_id]);
 },
 'format' => 'raw',

]

It is possible to get the username?

Thank you

Advertisement

Answer

In the User class:

public function getParent(){
   return $this->hasOne(User::class,['id'=>'parent_id']);
}

In the gridView:

[
    'attribute' => 'parent.id', // or parent.first_name (whatever is relevant to you)
    'value' => function($model) {
       if(isset($model->parent->id)) // or parent->first_name (whatever is relevant to you)
         return Html::a(Html::encode($model->parent->id), 
             ['view', 'id' => $model->parent->id]);
      return "not found";
     },
    'format' => 'html',
]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement