Search code examples
laravelpostgresqllaravel-query-builder

How to get the sum of columns from a group of records in a join?


I have a request that returns documents to me. I would like to join the sums of goods of each document and summarize them.

It looks like this:

There are documents.

  +-------------+----------+
  | document_id | owner_id | 
  +-------------+----------+
  | 52f20e4d    | ef27737d |  
  | 3bfdc5aa    | ef27737d |   
  +-------------+----------+

Products are attached to each document.

  +-------------+-------------+-----------+
  | product_id  | document_id | total_sum |
  +-------------+-------------+-----------+
  | b60624a7    | 52f20e4d    | 10        |
  | fcc21801    | 52f20e4d    | 5         |
  | d5cbe99d    | 3bfdc5aa    | 3         |
  | 5e537533    | 3bfdc5aa    | 4         |
  +-------------+-------------+-----------+

My php code:

$result = DB::table('documents as docs')->leftJoin('products as t_products', function($join) {
    $join->on('t_products.document_id', '=', 'docs.document_id');
})->where('docs.owner_id', '=', $currentUserId)->select('docs.document_id', 't_products.total_sum')
    ->get();

return response()->json($result);

I get the following:

[
  {
      "document_id": "52f20e4d",
      "total_sum": "5"
  },

  {
      "document_id": "52f20e4d",
      "total_sum": "10"
  },

  {
      "document_id": "3bfdc5aa",
      "total_sum": "4"
  },

  {
      "document_id": "3bfdc5aa",
      "total_sum": "3"
  }
]

But I would like to see only two entries in which the total_sum will be summarized.

Like this:

[
    {
        "document_id": "52f20e4d",
        "total_sum": "15"
    },

    {
        "document_id": "3bfdc5aa",
        "total_sum": "7"
    }
]

Solution

  • Add group by document id and sum of total sum

    $result = DB::table('documents as docs')
        ->leftJoin('products as t_products', function($join) {
            $join->on('t_products.document_id', '=', 'docs.document_id');
        })
        ->where('docs.owner_id', '=', $currentUserId)
        ->selectRaw('docs.document_id, sum(t_products.total_sum) as total_sum')
        ->groupBy('docs.document_id')
        ->get();