Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

peterpan26's avatar

subtotal and total laravel 3 tables join and groupby a varchar field

pseudo code help me solve this issue suppose i have 3 tables : tableOne | tableTwo | tableThree all the tables have : id | name | number i need to join the three tables, group them by name, and display the subtotal of number for each name, and a total at the end of all name number.

 $query = DB::table('tableOne')
->selectRaw('name,sum(tableOne.number + tableTwo.number + tableThree.number) as numberSum')
->join('tableTwo', '=', 'tableOne.id', '=', 'tableTwo.id')
->join('tableThree', '=', 'tableTwo.id', '=', 'tableThree.id')
->groupBy('name')
//blade
@foreach ($query as $item)
<td> {{$item->name}} </td>
<td> {{$item->numberSum}} </td>
@endforeach
0 likes
2 replies
jlrdw's avatar

You recently asked a similar question. Have you thought about taking some of the free training offered here.

But things like grand totals and summaries are separate queries. And line items are done in the query, I gave a short example in the other post of sum.

Edit:

This site has excellent sql tutorials and example: https://www.mysqltutorial.org/mysql-sum/

peterpan26's avatar

if i put on search engine : "expenses tracking table image" i get the end product , what i asked is different , i need to group by name, edit: sorry i didnt saw that you included some code below ill try it out thanks

Please or to participate in this conversation.