Reputation: 441
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
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
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