我用laravel制作订单管理系统。这是我的表结构,当用户下订单时,控制器将填充2个表1- orders ,2- orderitems在orders表中有2个字段user_id和总(价格)。在orderitems中,控制器将为产品示例创建不同的列,如果用户放置2种产品而不是控制器将在orderitems表中创建2行,则有5个字段:order_id、product_id、quantity、price、totalE 217(针对特定产品)。
这是我的订单表

这是我的订单表

疑问在于,我如何添加订单表的不同列的价格,并将其显示在订单表中,这是我的OrderController
public function store(Request $request)
{
$order = Order::create([
'user_id' => $request->input('user_id'),
'total' => **Doubt here**,
]);
$size = count(collect($request)->get('quantity'));
for ($i = 0; $i < $size; $i++) {
$orderitem = Orderitem::create([
'order_id' => $order->id,
'product_id' => $request->get('product_id')[$i],
$quantity = $request->get('quantity')[$i],
'quantity' => $quantity,
$price = Product::find($request->get('product_id')[$i])->price,
'price' => $price,
'total' => $quantity * $price,
]);
}
return redirect()->route('orders.index');
}发布于 2021-06-12 10:36:46
在你的情况下,我想这样会好的
public function store(Request $request)
{
$order = Order::create([
'user_id' => $request->input('user_id'),
'total' => 0,
]);
$total = 0;
$size = count(collect($request)->get('quantity'));
for ($i = 0; $i < $size; $i++) {
$orderitem = Orderitem::create([
'order_id' => $order->id,
'product_id' => $request->get('product_id')[$i],
$quantity = $request->get('quantity')[$i],
'quantity' => $quantity,
$price = Product::find($request->get('product_id')[$i])->price,
'price' => $price,
'total' => $quantity * $price,
]);
$total += $orderitem['quantity']*$orderitem['price'];
}
$order['total'] = $total;
$order->save()
return redirect()->route('orders.index');
}但是在一些更现实的情况下,scenario.we会做更复杂的订单计算,比如discocunt.so,我们会知道订单总数,然后再保存到数据库中。
如果你有更多的question.please评论给我。
发布于 2021-06-12 11:12:53
如果使用的是关系,则可以执行以下操作
$order = Order::create([
'user_id' => 1,
]);
$order->product()->sync([
1=>['quantity'=>2, 'price'=>20,'total'=>40],
2=>['quantity'=>1, 'price'=>10,'total'=>10],
]);
$order->total=$order->product()->sum('total');
$order->save();因为我在其他帖子中发布了关系,这与此有关,那么你可以做上面的方法。参考文献:Attempt to read property "price" on null in laravel?
https://stackoverflow.com/questions/67947871
复制相似问题