Answer the question
In order to leave comments, you need to log in
Yii2, Grid view, Label - how to make a label from several fields by foreign key?
The example is rather trivial.
I have two tables. I display services, they have a user id. Instead of id, I want to display the last name and first name, which are stored in the users table.
I follow this instruction:
php-lessons.com/blog/2016/06/06/yii2-view-data-ral...
created a function in the service model:
// получаем пользователя по ID
public function getUser() {
return ($this->hasOne(UserRecord::className(), ['id' => 'user_id']));
}
...
array('attribute'=>'user_id','filter'=>$users,'label'=>'User','value'=>('user.last_name')),
...
Answer the question
In order to leave comments, you need to log in
You need to create a new method in the User model:
Alternatively, create an anonymous function in the view:
public function getFullName(string $separator = ' '): string
{
return implode($separator, array_filter([
$this->firstName,
$this->middleName,
$this->lastName
]));
}
'value'=> function($model) {
return $model->first_name .' '. $model->last_name
}
user.fullName
//или
$user->getFullName(', ')
value => function (value) { return value->user->lastName .’ ‘. value->user->firstName;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question