1

I have stuffs table where will be saved only stuff title.

Stuffs table:

id
title

Also I've user_stuffs table where each user has n stuff volume.

User stuffs table:

id
stuff_id
user_id
volume

How I can SUM each stuffs volumes and get like this result:

{
  "title": "Stuff Title",
  "total": 7634
}

I tried using only sql exec like this query but how I can do it correctly in Laravel?

SQL:

SELECT 
    stuffs.id, 
    stuffs.title, 
    SUM(user_stuffs.volume) AS total 
FROM `user_stuffs`
INNER JOIN stuffs ON user_stuffs.stuff_id = stuffs.id
GROUP BY user_stuffs.stuff_id
Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125

1 Answers1

0

Try this

DB::table('user_stuffs')
    ->Join('stuffs','stuffs.id','=','user_stuffs.stuff_id')
    ->select('stuffs.id','stuffs.title',DB::raw('SUM(user_stuffs.volume) AS total'))
    ->groupBy('user_stuffs.stuff_id','stuffs.id', 
    'stuffs.title')
    ->get();
Basharmal
  • 1,313
  • 10
  • 30
  • Error `Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1055 'database.stuffs.id' isn't in GROUP BY (SQL: select `stuffs`.`id`, `stuffs`.`title`, SUM(user_stuffs.volume) AS total from `user_stuffs` inner join `stuffs` on `stuffs`.`id` = `user_stuffs`.`stuff_id` group by `user_stuffs`.`stuff_id`)'` – Andreas Hunter Apr 04 '21 at 11:03
  • I have updated the answer give it a try and let me know – Basharmal Apr 04 '21 at 11:59