php - 在 laravel 5.8 的 foreach 循环中存储数据
问题描述
我在存储数据方面需要您的帮助。
我有几个产品的购物车,现在我想Order
通过单击提交按钮将所有这些产品同时存储在表中
我的观点blade.php
此视图显示购物车中的所有产品,我需要将这些信息存储在Order
表中
<form action="{{route('order.store')}}" method="post">
@csrf
@foreach ($cart as $ct)
<input type="text" name="product_id" value="{{$ct->id}}" hidden>
<input type="text" value="{{$ct->color}}" name="color" >
<input type="text" value="{{$ct->size}}" name="size" >
<input type="text" value="{{$ct->price}}" name="price" >
@endforeach
<button type="submit">submit</button>
</form>
在我的Order
表格中,我需要填写这 4 列:product_id、color、size 和 price。
我的 foreach 循环从Cart
表中获取数据,并且所有数据都显示没有错误。
我的问题是,我如何Order
只需单击一次提交按钮就可以将这些数据存储到我的表中?我应该在我store function
的 in 中写什么OrderController
?
如果我的购物车有 3 件产品,那么我的期望值是Order
表格,如下所示:
id----product_id----size----color---price---+
---------------------------------------------
1 1 abc xyz 123
---------------------------------------------
2 2 abc2 xyz2 456
---------------------------------------------
3 3 aaa bbb 789
感谢您的帮助!
解决方案
D B:
Order:
user_id
created_at
...
orderProducts:
price
color
size
order_id (relation)
product_id (relation)
...
看法
<form action="{{route('order.store')}}" method="post">
@csrf
@foreach ($cart as $ct)
<input type="text" name="products[]" value="{{$ct->product_id}}" hidden>
<input type="text" value="{{$ct->color}}" name="color[]" >
<input type="text" value="{{$ct->size}}" name="size[]" >
<input type="text" value="{{$ct->price}}" name="price[]" >
@endforeach
<button type="submit">submit</button>
</form>
控制器功能存储
$order= new Order;// change the model here
// .. complete your information's like user id or created_at
$order->save();
foreach($request->products as $key=>$product_id)
{
$product = Product::findOrFail($product_id); // validations the product id
// get your information's from db (color,size,price) don't trust get information's from user .
// $product->price , $product->color .... or get from cart
//from cart direct $color[$key] or $price[$key] or $size[$key] "I don't recomend to use this point"
// must be create new table
$orderProducts=new orderProducts; // create new table ordersProducts
$orderProducts->price = $product->price;
// .. complete your information's
$orderProducts->order_id = $order->id; // primary key
$orderProducts->product_id= $product->id;
$orderProducts->save();
}
注意: - 如果在“findOrFail”步骤中失败,您需要使用 try-catch 记录信息,或者更改为查找,然后如果在表中未找到产品,则记录订单未完成并向用户显示错误
推荐阅读
- python - 如何在 maya python ls 命令中选择顶点?
- android - 即使指定了 android:screenOrientation="portrait",Android 也以横向方式启动活动(来自库项目)
- ruby-on-rails - 在多个每个循环内/以上向哈希添加值
- typescript - TypeScript 接口属性 @version
- c# - 情节提要仅在第二个条件下触发一次
- javascript - 使用 Promise 实现简单的请求链逻辑
- python - 如何将变量作为上下文传递给 IBM Cloud Watson Assistant V2?
- android - 谷歌开发者注册不起作用
- ios - 应用终止时CoreBluetooth建立外围连接
- types - 在 Kotlin 和 MVP Android 中使用泛型