Мне нужно перебрать массив и минус needed_quantity
от каждого объекта
ех. needed_quantity = 22
и в этом массиве есть три объекта, количество каждого объекта = 10
так будет примерно так.
- взять 10 штук из expire_date = 2019-03-02 инвентарь станет 0
- взять 10 предметов из expire_date = 2019-03-10 инвентарь станет 0
- взять 2 штуки из expire_date = 2019-03-11 инвентарь станет 8
Вот массив
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"
]
}
]
}