$order_temporaries = DB::table('order_temporary_tb') ->distinct('bidan_id') ->select('order_temporary_tb.bidan_id as bidan','order_temporary_tb.id as id') ->where(function($query){ $query->where('status','0') ->where('status','1') ->where('status','3'); }) ->get(); foreach ($order_temporaries as $v) { $bidan = DB::table('bidan_tb') ->where('id',$v->bidan) ->first(); $sum_order_item_temporary = DB::table('order_item_temporary_tb') ->sum('total_price'); $balance = $bidan->cust_limit - $sum_order_item_temporary; DB::table('bidan_tb') ->where('id',$v->bidan) ->update(['available_balance'=>$balance]); } $orders = DB::table('order_tb') ->distinct('bidan_id') ->select('order_tb.bidan_id as bidan') ->where(function($query){ $query->where('status','0') ->orWhere('status','1') ->orWhere('status','2') ->orWhere('status','3') ->orWhere('status','4') ->orWhere('status','5'); }) ->get(); foreach ($orders as $order) { $bidan = DB::table('bidan_tb') ->where('id',$order->bidan) ->first(); $transactions = DB::table('order_tb') ->where('bidan_id',$order->bidan) ->where(function($query){ $query->where('status','0') ->orWhere('status','1') ->orWhere('status','2') ->orWhere('status','3') ->orWhere('status','4') ->orWhere('status','5'); }) ->sum('price_to_bidan'); $balance = $bidan->cust_limit - $transactions; DB::table('bidan_tb') ->where('id',$order->bidan) ->update(['available_balance'=>$balance]); }