R
R
Ruslan Absalyamov2019-02-24 17:32:34
Yii
Ruslan Absalyamov, 2019-02-24 17:32:34

Why is the data from the linked table not showing?

It seems to have done everything right, but gridView writes not set. Although there is a given user in the database.
5c72aa3a34992559446582.pngHere is the table itself with key derivation.
My implementation
In the news model

public function rules()
    {
        return [
            ...
            [['status', 'user_id'], 'integer'],
           ...
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

In NewsSearch
public function search($params)
    {
        $query = News::find()->with('user');
        ...
    }

and gridView
<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ...
            [
                'attribute' => 'user_id',
                'label' => 'Автор',
                'value' => 'user.username'
            ],
            ...
        ],
    ]); ?>

Can't display email

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2019-02-24
@rusline18

apparently not for all user_id there is a corresponding user or, more likely, somewhere user_id = null.
So I would make a getter in news and check if there is a user there or not, and then I would try to pull his username
for example:

public function getUserName()
    {
        return $this->user ? $this->user->username : 'не задан';
    }

well, in the gridView, respectively, instead of 'value' => 'user.username'it will be 'value' => 'userName'or even simpler
'userName', and specify the label in the model with others

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question