column sum function not working properly after forach loop

Viewed 49

I want to get sums of column "quantity" for 2 different product ids.

I have a nested "for each loop" to update multiple product id. after finishing the nested "foreach" I am trying to get the sums of the "quantity" column for the respective ids.

for example : there are 2 product ID 1 & 2. each time I submit the form, it will either create a new row/rows or else if already exists(transfer_id) then will update. After updating the row/rows, there is another foreach loop to get the sum of the "quantity" column for both product 1 and product 2. The problem is, I am getting same sum value for both product ID, while I should Get sum 88 for product 1 and 52 for product 2, I am getting 53 for both product

The table looks like :

enter image description here

My codes are :

foreach($request->transfer as $key => $value){
            
    $update_prdct_wrhs = Transfer::where('id',$request->transfer[$key] 
         ['transfer_id'])->update([
                'from'      => 0,
                'to'        => $request->transfer[$key]['storage_id'],
                'supply_id' => $id,
                'status'    => $request->transfer[$key]['status']
         ]);

    foreach($request->transfer[$key]['product'] as $n_key => $n_value){

          $product_ids[] = $request->transfer[$key]['product'][$n_key]['product_id'];
          $product_quantities[] = $request->transfer[$key]['product'][$n_key] 
          ['quantity'];
          $storage_ids[] = $request->transfer[$key]['storage_id'];

          $input['storage_id']   = $request->transfer[$key]['storage_id'];
          $input['product_id']   = $request->transfer[$key]['product'][$n_key] 
          ['product_id'];
          $input['transfer_id']  = $request->transfer[$key]['transfer_id'];
          $input['quantity']     = $request->transfer[$key]['product'][$n_key] 
          ['quantity'];

          $supply_to_storage[] =  StorageProduct::updateOrCreate(['transfer_id'=> 
          $request->transfer[$key]['transfer_id']],$input); 
    }
            
}

foreach($supply_to_storage as $d => $k){
     $a[] = $supply_to_storage[$d]->product_id;
}
        
$product_ids = array_unique($a);

foreach($product_ids as $fg => $dingdong){
    $sum_product_stock[] = StorageProduct::where('product_id',$product_ids[$fg])- 
    >sum('quantity');
}
0 Answers
Related