从模型中的关系中获取全名

Get the full name from relation in model

我有模特博客,我在那里有关系:

public function getRelUser()
    {
        return $this->hasOne(UrUser::className(), ['Id' => 'Rel_User']);
    }

我想在 gridView 的 blogView 索引中使用 fullName:

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

            'Id',
            'Title',
            'Description',
            'Rel_User',
            [
        'attribute' => 'Rel_User',
        'value' => 'relUser.Name'
        ], 
            'CreatedAt',
            // 'IsDeleted',

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

这个 return 列中只有我的名字。我要return全名

在 UrUser 模型中添加新方法:

class UrUser extends \yii\db\ActiveRecord
{
    ....

    public function getFullName()
    {
        return $this->name .' '. $this->last_name;
    }
}

并像这样在您的视图中使用它:

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

            'Id',
            'Title',
            'Description',
            'Rel_User',
            [
                'attribute' => 'Rel_User',
                'value' => function ($model) {
                    return $model->relUser->getFullName();
                },
             ], 
            'CreatedAt',
            // 'IsDeleted',

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

试试这个

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

            'Id',
            'Title',
            'Description',
            'Rel_User',
            [
        'attribute' => 'Rel_User',
        'value' => function($model) { 
              return $model->relUser->name  . " " . $model->relUser->last_name ;
            },
        ], 
            'CreatedAt',
            // 'IsDeleted',

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

更新 CDetailView。这应该有效

[
  'label'=>'Full Name',
  'value'=>'$data->relUser->name . " " . $data->relUser->last_name',
]