Uploaded image for project: 'PHP ORMs'
  1. PHP ORMs
  2. PHPORM-69

Add support for Query\Builder::withCount()

    • Type: Icon: New Feature New Feature
    • Resolution: Unresolved
    • Priority: Icon: Unknown 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
          }
        }
      ]);

            Assignee:
            Unassigned Unassigned
            Reporter:
            jerome.tamarelle@mongodb.com Jérôme Tamarelle
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: