Yii2: there's no way to limit results in a hasMany relation

Created on 27 Mar 2016  路  3Comments  路  Source: yiisoft/yii2

i understand how hasMany works so i don't see an easy way to solve this. however it seems strange that you can't properly limit the result rows of a hasMany relation per record.

for example, if i do:

Post::find()->with( ['comments'] )->where( ['id' => '1,2,3,4,5'] )->all();

and i have a getComments relation defined in Post like this:

$this->hasMany( Comment::className(), ['postId' => 'id'] )->limit( 10 );

then the original query only returns 10 comments TOTAL instead of 10 comments per post. is there proper way to limit hasMany rows per record? obviously i can limit manually in the code but in the case of a great deal of hasMany records i'd rather not be working with a huge data set all at once.

question

All 3 comments

do you know how to do it in plain sql?

_This is an automated comment, triggered by adding the label question._

Please note, that the GitHub Issue Tracker is for bug reports and feature requests only.

We are happy to help you on the support forum, on IRC (#yii on freenode), or Gitter.

Please use one of the above mentioned resources to discuss the problem.
If the result of the discussion turns out that there really is a bug in the framework, feel free to
come back and provide information on how to reproduce the issue. This issue will be closed for now.

You can make a Class extend to Comment锛宎nd add a function cover the find function:

class LastComment extends Comment
{
    public static function find()
    {
        return parent::find()->orderBy(['id' => SORT_DESC])->limit(10);
    }

}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

indicalabs picture indicalabs  路  3Comments

Locustv2 picture Locustv2  路  3Comments

psfpro picture psfpro  路  3Comments

Kolyunya picture Kolyunya  路  3Comments

newscloud picture newscloud  路  3Comments