Answer the question
In order to leave comments, you need to log in
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']);
}
$trademark->news->orderBy(['created_at' => SORT_DESC])->limit(4)->all()
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question