A
A
Alexander Laikov2020-12-03 00:05:38
Yii
Alexander Laikov, 2020-12-03 00:05:38

Yii2. Why does it output NULL on eager loading?

Good afternoon!
The User model has a relationship:

public function getMessage () {
        return $this->hasMany ( Message::className () , [ 'to_id' => 'id' ] );
    }

In the Message model:
public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'to_id']);
    }


In the controller, we execute the request:
$models = Message::find()->with('user')->where(['from_id' => Yii::$app->user->identity->id , 'type' => 2])->orderBy([ 'time' => SORT_ASC ])->limit(15)->all();


And in view:
foreach ($models as $model) {
var_dump($model->user)
}


And as a result we get NULL
What is my problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kulay, 2020-12-04
@Kulay

Try swapping ['id' => 'to_id'] or write together with the table name: ['user.id' => 'message.to_id'].
The problem looks like there is simply no connection, perhaps the id is not correctly connected

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question