I have a table with name transaction (Model: Transaction). Here is my table structure:
Type | Quantity |
---|---|
+ | 10 |
– | 4 |
+ | 15 |
– | 15 |
Here I want sum of total quantity, where all the -
should be subtracted and all the +
should be added. How can I get ?
I have added all +
(this is purchase) and subtracted -
(this is sale) with 2 different queries this way:
Transation::sum('Quantity')->where('Type','+') - Transation::sum('Quantity')->where('Type','-')
.
Is there any better and single query than multiple queries ?
3
Answers
You can perform the calculation directly on your query using
selectRaw
and do sql syntax.or group the table by
Type
then perform the calculation in laravel collectionThis can be done by accessing your data with your eloquent model. Then you can iterate through each and check the value by accessing the properties and operating based on that.
Just a note on using
Model::all()
, if you have many elements you should usechunk
instead.all()
will load all the data into memory, which can be exceeded with too many entries.You can read more about that here: Select all from table with Laravel and Eloquent
Try calculating in MySQL itself using Laravel’s
selectRaw