-2

Hi Guys this is my Table called "inputs". I would like to sum the values having the same TID :

re   |  in_ID|   Value  |
========================= 
 1   |   1   |   3  | 
 2   |   1   |   3  |  
 3   |   1   |   4  |  
 4   |   1   |   5  |  
 5   |   2   |   3  |  
 6   |   2   |   3  |  
 7   |   2   |   2  |  
 8   |   2   |   2  |

my result should be like that

in_ID| sum(Value)|
==================   
 1   |   14      |   
 2   |   20      |

my attempt is:

public function sum(){        
    return production_input::select('in_id' , 'value')->sum('value')->groupBy(['in_id']);
}  
Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40

1 Answers1

1

Try this way.

public function sum(){
        return production_input::select([\DB::raw("SUM(value) as value"), 'in_id'])
                                 ->groupBy('in_id')
                                 ->get();
}  
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
  • 1
    Thanks a lot . can you describe how actually this work? – Nouman Ahmad Feb 28 '20 at 07:24
  • can this work with out Raw query ie \DB::raw("SUM(value) as value"), 'in_id']) ->groupBy('in_id') – Nouman Ahmad Feb 28 '20 at 07:25
  • when you use groupBy with `in_id` it'll convert it in `in_id` group wise. after sum function will sum `value` in-group. and select function will select `in_id` and `value` of sum. in return you'll get only `in_id` with sum of in_id :) – Dilip Hirapara Feb 28 '20 at 07:27
  • `can this work with out Raw query` yes it'll. use `->selectRaw('sum(value) as sum, in_id')` – Dilip Hirapara Feb 28 '20 at 07:28