采购订单应用:如何让order_items单次操作获取orders表最新ID?
Fixing Order ID Assignment for Order Items
Hey there! I see the issue here - right now you're trying to pull order_id from the request input, but that doesn't make sense because you just created the order in this very request. The new order's ID is already available on the $orders model instance you created, so we can use that directly for all related order items.
Here's how to modify your store function correctly:
public function store(Request $request) { // Create the main order first $orderData = $request->only( 'user_id', 'status_id', 'currency_id', 'company_id', 'purchase_no', 'notes', 'delivery_date', 'publish' ); $orderData['grandtotal'] = (float) str_replace(',', '', $request->grandtotal); $order = Orders::create($orderData); // Renamed to $order for clarity // Process order items $input = $request->all(); // Use foreach to avoid index issues (safer than for loop) if (isset($input['quantity']) && is_array($input['quantity'])) { foreach ($input['quantity'] as $index => $quantity) { // Skip empty/invalid quantities if (empty($quantity) || !is_numeric($quantity)) continue; // Make sure all related fields exist for this index to avoid errors if (!isset($input['product_id'][$index], $input['product_code'][$index], $input['product_name'][$index], $input['cost'][$index], $input['total_cost'][$index])) { continue; // Skip incomplete items } $itemData = [ 'order_id' => $order->id, // Use the newly created order's ID here! 'product_id' => $input['product_id'][$index], 'product_code' => $input['product_code'][$index], 'product_name' => $input['product_name'][$index], 'cost' => $input['cost'][$index], 'quantity' => intval($quantity), 'total_cost' => (float) str_replace(',', '', $input['total_cost'][$index]), ]; Orderitems::create($itemData); } } return redirect()->route('orders.index'); }
Key Changes Explained:
- Use the new order's ID: Instead of pulling
order_idfrom the request, we use$order->id- this is the auto-generated ID from theorderstable right after creating the record. - Safer looping with foreach: Swapped the
forloop for aforeachto avoid off-by-one errors (your original$i <= count(...)would loop one extra time, leading to undefined index errors). - Added safety checks: Added checks to make sure all required fields exist for each item index, preventing unexpected errors if the frontend sends incomplete data.
- Renamed variable for clarity: Changed
$ordersto$ordersince it's a single order instance, making the code easier to read.
This way, every order item you create will automatically be linked to the new order you just saved, all in one request.
内容的提问来源于stack exchange,提问作者SleepWalker
相关产品推荐
相关产品推荐

