A
A
Askar Fuzaylov2015-06-06 16:15:39
Yii
Askar Fuzaylov, 2015-06-06 16:15:39

How to get data from relay with hasMany and viaTable?

Hello dear.
I can't get data from the associated model.
There is a model with connection:

class Post extends ActiveRecord {

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

/**
     * @return \yii\db\ActiveQuery
     */
    public function getPage()
    {
        return $this->hasOne(Page::className(), ['id' => 'page_id'])
            ->viaTable('cube', ['post_id' => 'id']);
    }
}

If I get one model I get data from the associated model:
$model = Post::findOne(123);
// получаем ID страницы
// Разницы нет использую ли hasMany или hasOne
$model->page->id;

But if I get an array of models and access each one individually, I can't get data from related models.
$models = Post::find()->all();

foreach($models as $model) {
    // Тут у меня свойство page == NULL (hasOne)
    // или page ровняется пустому массиву (hasMany)
    // Разницы нет использую ли hasMany или hasOne
    $model->page->id;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
matperez, 2015-06-06
@matperez

Everything seems to be correct. And try eager loading: Post::find()->joinWith('page')->all().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question