Laravel 5如何将两个相关表插入(多个)到一个查询中

I have a table which is Order and Product

  • orders table: id, order_name
  • products table: id, orders_id, product_name

In my model: Order can have many products. Product belongs to order

Below is my view:

<input type="text" name="order_name"> 
<input type="text" name="product_name">

<input type="text" name="order_name"> 
<input type="text" name="product_name">

From the view above, I have two forms whereby the users can add two form with two input.

Now my problem is how do I write the logic in the controller?

I just know the way to write insert one order with multiple product. But I don't know how to insert multiple orders with its related product.

You should use a pivot table, as it's a many to many relationship between the two tables.

Since a product belongs to not just one order but many and an order can have many products, pivot table is the way to go.

See here if you don't know what a pivot table is : http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

They explain it in an example very similar to yours.

Try this:

$order = new Order();
$order->order_name = $request->order_name;

if($order->save()) {
   $product = new Product();
   foreach($request->product_name as $product) {
     $product->product_name = $product;
     $product->order_id = $order->id;
     $product->save();
   }
}