-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: Laravel
-
None
withCount function is a Laravel Eloquent feature that simplifies counting of related models.
https://laravel.com/docs/10.x/eloquent-relationships#counting-related-models
Post::select('posts.*')->->withCount('comments')->get();
Generates the following SQL (using subquery)
select "posts".*, (select count(*) from "comments" where "posts"."id" = "comments"."post_id") as "comments_count" from "posts"
We need an $lookup aggregation to add a computed field in MongoDB.
db.posts.aggregate([ { $lookup: { from: "comments", localField: "_id", foreignField: "post_id", as: "comments" } }, { $addFields: { comments_count: { $size: "$comments" } } }, { $project: { comments: 0 // Exclude the "comments" array from the final result if not needed } } ]);
- depends on
-
PHPORM-103 Integrate Aggregation builder into Laravel library
- Development Complete