我需要遍历数组,并从每个对象中减去needed_quantity
例如needed_quantity = 22
此数组中有三个对象,每个对象数量= 10
所以会是这样。
这是数组
foreach ( $orderProducts as $order_product ) {
//This the quantity in order details.
$orderQuantity = $order_product->quantity;
$currentInventors = Inventory::whereProductId( $order_product->product_id )->get()->sortBy( 'expire_date' );
if ( $currentInventors != null ) {
foreach ( $currentInventors as $currentInventory ) {
$takeQuantity = $currentInventory->inventory - $orderQuantity; //10-15 = 5
if ( $currentInventory->inventory >= $orderQuantity ) {
Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => $takeQuantity ] );
break;
} elseif ( $currentInventory->inventory < $orderQuantity ) {
Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => 0 ] );
//$takeQuantity = $currentInventory->inventory - $orderQuantity; //10-15 = -5
$newQuantity = $orderQuantity - $currentInventory->inventory; //15-10 = 5
if ( $currentInventory->inventory >= $orderQuantity ) {
Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => $newQuantity ] );
break;
}
}
}
}
}
现在,当我更新时,我得到了所有三个对象值0
更新数组
Collection {#715
#items: array:3 [
0 => Inventory {#744
#fillable: array:3 [
0 => "product_id"
1 => "inventory"
2 => "expire_date"
]
#attributes: array:6 [
"id" => 10
"product_id" => 857
"inventory" => 10
"expire_date" => "2019-03-02"
"created_at" => "2019-03-07 11:13:21"
"updated_at" => "2019-03-27 11:16:01"
]
}
1 => Inventory {#745
#fillable: array:3 [
0 => "product_id"
1 => "inventory"
2 => "expire_date"
]
#attributes: array:6 [
"id" => 13
"product_id" => 857
"inventory" => 10
"expire_date" => "2019-03-10"
"created_at" => "2019-03-10 16:53:21"
"updated_at" => "2019-03-27 11:16:01"
]
}
2 => Inventory {#746
#fillable: array:3 [
0 => "product_id"
1 => "inventory"
2 => "expire_date"
]
#attributes: array:6 [
"id" => 16
"product_id" => 857
"inventory" => 0
"expire_date" => "2019-03-11"
"created_at" => "2019-03-10 17:01:14"
"updated_at" => "2019-03-27 11:16:01"
]
}
]
}
答案 0 :(得分:2)
这是我赢的解决方案。
我的错是我没有在每次循环中都减少$orderQuantity
。
$orderProducts = OrderDetail::whereOrderListsId( $deliveryList->order_lists_id )->get();
foreach ( $orderProducts as $order_product ) {
//This the quantity in order details.
$orderQuantity = $order_product->quantity;
//Here we selected the oldest expire date of the same product in the inventory.
$currentInventors = Inventory::whereProductId( $order_product->product_id )->get()->sortBy( 'expire_date' );
if ( $currentInventors != null ) {
foreach ( $currentInventors as $currentInventory ) {
$takeQuantity = $currentInventory->inventory - $orderQuantity;
if ( $currentInventory->inventory >= $orderQuantity ) {
Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => $takeQuantity ] );
break;
} else {
$orderQuantity = $orderQuantity - $currentInventory->inventory;
Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => 0 ] );
}
}
}
}
现在工作正常。