[英]How do I update new collection values?
I need a way to update a collection that I am getting from the html form.我需要一种方法来更新从 html 表单中获取的集合。
I have an array of我有一个数组
Product ids:
array:3 [
0 => "1"
1 => "2"
2 => "3"
]
Product quantity:
array:3 [
0 => "15"
1 => "5"
2 => "7"
]
Product Price:
array:3 [
0 => "12.00"
1 => "2.50"
2 => "4.00"
]
I am storing/saving the values to the database with something like this:我正在将值存储/保存到数据库中,如下所示:
$product_ids = $request->get('product_ids');
$product_prices = $request->get('product_prices');
$product_quantities = $request->get('product_quantities');
$product_descriptions = $request->get('product_descriptions');
for ($i = 0; $i < sizeof($product_ids); $i++) {
$item = new Order_item;
$item->order_id = $order->id;
$item->product_id = $product_ids[$i];
$item->unit_price = $product_prices[$i];
$item->description = $product_descriptions[$i];
$item->quantity = $product_quantities[$i];
$item->save();
}
You can find the record based on id and then save the changed data:您可以根据id找到记录,然后保存更改的数据:
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
From https://laravel.com/docs/7.x/eloquent#updates来自https://laravel.com/docs/7.x/eloquent#updates
If you're using order_id as the key, then use a where() statement with first():如果您使用 order_id 作为键,则使用带有 first() 的 where() 语句:
$order = App\Order_item::where('order_id', 1)->first();
I fixed the issue with something like this:我用这样的方法解决了这个问题:
$product_ids = $request->get('product_ids');
$product_prices = $request->get('product_prices');
$product_quantities = $request->get('product_quantities');
$product_descriptions = $request->get('product_descriptions');
Fetched the values using $request->get
.使用$request->get
值。
And updated the values using a for loop.并使用 for 循环更新值。
for ($i = 0; $i < sizeof($product_ids); $i++) {
Order_item::where('order_id', $id)
->where('product_id', $i + 1)->update(
[ 'quantity' => $product_quantities[$i],
'unit_price' => $product_prices[$i],
'description' => $product_descriptions[$i],
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.