提前限制结果在Laravel

i did a lots of research and still i didn't solve the problem, Hopefully some of you can help me.

i have a table Post and a table Comment with the normal relation Post Has Many Comments

I set up the following query for get 10 posts with the relative comments:

Post::with('comments')->limit(10)->get();

Well it work, but still is not my final result because i want limit even the comments to 5 For each post

So far i tried this query for limit my comments even if logically it will limit only 5 comments for all posts. In fact it does how i guessed.

Post::with(['comments' => function($comments){

       $comments->limit(5);

}])->limit(10)->get();

Maybe with eloquent this kind of query is not possible, but how can i make it work even with 2 different queries and merge the results?

Any kind of help will be really appreciated.

Thanks

What I think you need to do, is limit the amount of posts in the relationship.

Something like this would do it:

public function comments()
{
    return $this->hasMany('Comment')->limit(5);
}

Did not test this though, so it might not work.

Please use

    $lines = \Category::where('status', \Category::STATUS_PUBLISH)
            ->with(['firstThreeComment'])
            ->get()
            ->map(function( $category ){
                $category->firstThreeComment = $category->firstThreeComment->take(3);
                return $category;
});

Solution is here: http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/

Something like this: return $this->comments()->latest()->nPerGroup('post_id', 5);