从模型中获取关系的全名

时间:2016-03-04 11:43:13

标签: php gridview view yii2 relation

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

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

这只返回列中的名称。我想要返回全名。

2 个答案:

答案 0 :(得分:4)

试试这个

<?= 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',
]

答案 1 :(得分:3)

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