I have a categories table. every category has some posts.
I want to get categories with their last 10 posts.
So I tried this:
Category::query()->with(['posts' => function($q) {
$q->take(10);
}])->get();
The problem is instead of putting 10 posts in each category record, it returns a total of 10 posts in all categories items.
Expected:
C1:
id: 1
posts: 10 post
C2:
id: 2
posts: 10 post
What I got
C1:
id: 1
posts: 4 post
C2:
id: 2
posts: 6 post
2
Answers
Would try this version
In fact, this is not a trivial task. The code you provided generates two queries:
The 2nd query selects only 10 posts, not 10 per category.
To select 10 posts per category, you can make the following query:
Now let’s implement it through Laravel’s queryBuilder:
As a result, we still make only 2 queries and select only necessary posts (do not pull the entire table)