Umair Zahid
Umair Zahid

Reputation: 441

Laravel multiple hasmany relation limit issue

I have 3 collection pages,posts,comments and relation is

pages => hasmany => posts => hasmany =>comments

pages model relation

public function posts()
{
    return $this->hasMany('App\Models\PostsModel', 'page_id');
}

posts model relation

public function comments()
{
    return $this->hasMany('App\Models\CommentsModel', 'post_id')->limit(10);
}

Query

PagesModel::with('posts.comments')->get();

it supposes to take all page posts and 10 comments for each post, but it skips results, Many posts have multiple comments but unable to get comments.

Any solution or a better approach. Thanks

Upvotes: 2

Views: 310

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

There is no native support for this in Laravel.

I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit

Use the HasEagerLimit trait in both the parent and the related model.

class PostsModel extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class CommentsModel extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then you can apply ->limit(10) to your relationship.

Upvotes: 1

Snapey
Snapey

Reputation: 4110

Its a common question for which there is no easy answer. Read https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ for an explanation

Upvotes: 0

Related Questions