Reputation: 848
I have a table in my database called stocks. In the table, i have two columns product_id, supplied among other columns. So when i get a supply, i add the entries to my table and the table looking like so;
product_id supplied
1 10
2 15
5 5
2 12
4 10
5 12
2 5
1 12
4 12
Now i want to use laravel eloquent to select the stock by the product_id, returning the total number of items in stock like this;
product_id total_in_stock
1 22
2 32
4 22
5 17
Any assistance will be appreciated.
Upvotes: 0
Views: 208
Reputation: 2683
Use SUM and groupBy:
Stock
::selectRaw('product_id, SUM(supplied) as total_in_stock')
->groupBy('product_id')
->get();
Upvotes: 1