I intend to pull all the rows that have same order ID from an orderDetail table using the get() method and loop through to add all the values of the tax column to a $total_ variable. Then I planned to add the $total_ to the seller balance.
I want to get the sum of the tax values in column that get pulled out with the same order_id. I have tried to use the sum() but there seem to still be error. The only thing that work is when I used first() which only get the first row where my condition is true. but that way, I am only able to use one tax value. There are instances where I have two items with the same order_id (when we have different products in a cart). They come into the database with same order_id. So, I am now looking for a way to pull all rows with same order_id and then get the sum of the tax column.
if ($request->status == 'cancelled' && $order->payment_status == 'paid') {
$commissionHistoriesnow = \App\Models\CommissionHistory::where('order_id', $request->order_id)->get();
$total__ = 0;
foreach ($commissionHistoriesnow as $key => $commissionHistorynow) {
if($commissionHistorynow->admin_commission != null) {
$total__ = $commissionHistorynow->admin_commission;
}
}
$seller = Seller::where('user_id', $commissionHistoriesnow->seller_id)->first();
$seller->admin_to_pay = $total__;
$seller->save();
}
CodePudding user response:
You can use the sum method of the Builder to get a sum of that column for you without having to retrieve all the records and iterate them:
$total = CommissionHistory::where('order_id', $request->order_id)
->sum('admin_commission');
Additional:
Also, you could use the increment method on the Model to increment the 'admin_to_pay' field and update it in the database (which would fire Model events):
$seller->increment('admin_to_pay', $total);
If you are not worried about events and there is only the one record by this condition you could call increment on the builder itself to update the record you are querying for:
Seller::where('user_id', $commissionHistoriesnow->seller_id)->increment('admin_to_pay', $total);
Laravel 8.x Docs - Queries - Running Database Queries - Aggregates sum
Laravel 8.x Docs - Eloquent - Retrieving Single Models / Aggregates - Retrieving Aggregates sum
Laravel 8.x Docs - Queries - Update Statements - Increment & Decrement increment
