Add support for Query\Builder::withCount()

XMLWordPrintableJSON

    • Type: New Feature
    • Resolution: Unresolved
    • Priority: Unknown
    • None
    • Affects Version/s: None
    • Component/s: Laravel
    • None
    • None
    • None
    • None
    • None
    • None
    • None
    • 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
              Reporter:
              Jérôme Tamarelle
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Created:
                Updated: