D
D
des1roer2017-05-30 10:13:43
Yii
des1roer, 2017-05-30 10:13:43

Yii2 how to limit hasmany fetch?

in the model

public function getNews()
{
    return $this->hasMany(News::class, ['id' => 'news_id'])->viaTable('news_trademark', ['trademark_id' => 'id']);
}

a
$trademark->news->orderBy(['created_at' => SORT_DESC])->limit(4)->all()

does not work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vit, 2017-05-30
@des1roer

This is how it should be:
When you access the news property, under the hood, the query is already being executed and the result is returned.
Therefore, you need to refer to the getNews() method - it will return a query object on which you can set additional conditions and then call all() already.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question