【问题标题】:Laravel 5 How to insert (multiple) two related table into a single queryLaravel 5 如何将(多个)两个相关表插入到单个查询中
【发布时间】:2016-12-11 08:49:37
【问题描述】:

我有一张桌子是OrderProduct

  • 订单表:id, order_name
  • 产品表:id、orders_id、product_name

在我的模型中: Order 可以有多个 productsProduct 属于order

以下是我的看法:

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

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

从上面的视图中,我有两个表单,用户可以通过两个输入添加两个表单。

现在我的问题是如何在控制器中编写逻辑?

我只知道用多个产品插入一个订单的方法。但是我不知道如何用它的相关产品插入多个订单。

【问题讨论】:

  • 您能否发布您的订单模型、产品模型和视图的代码,以便更好地了解您要完成的工作并相应地为您提供输入。

标签: php laravel eloquent


【解决方案1】:

您应该使用数据透视表,因为它是两个表之间的多对多关系。

由于一个产品不仅属于一个订单,而且属于多个订单,而且一个订单可以包含多个产品,因此数据透视表是可行的方法。

如果您不知道什么是数据透视表,请查看此处:http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

他们用一个与你非常相似的例子来解释它。

【讨论】:

    【解决方案2】:

    试试这个:

    $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();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多