【问题标题】:How to save multiple rows to multiple database tables at onces如何一次将多行保存到多个数据库表
【发布时间】:2018-06-23 23:46:34
【问题描述】:

例如,我有“身份证、姓名、工资、性别、年龄”列。

  • 1,约翰,3,M,30
  • 2、安吉拉、5、F、26

如果我有 50 行这样的。如果我想保存姓名,请将工资存入表 1,并将性别和年龄存入表 2。在 laravel 文档查询/插入中,他们告诉我们创建一个数组并在其上放置值。但是我应该如何在同一个 foreach 中将一些值放入 table1 中,将其他值放入 table2 中。

foreach($test as $tests)
   {
    $data[] =[
                'name' => $tests->name,
                'wage' => $tests->wage,
                'sex' => $tests->sex,
                'age' => $tests->age
               ];                 

   }
  Products::insert($data);

这是正确的方法吗?我想不出正确的方法。

【问题讨论】:

标签: laravel eloquent


【解决方案1】:

您可以将loop 低谷数据和insert 转换为DB table

foreach($test as $tests)
{
    $product = new Products();
    $product->name = $tests->name;
    $product->name = $tests->name;
    $product->save();

    $another = new AnotherTableModel();
    $another->sex= $tests->sex;
    $another->age= $tests->age;
    $another->save();                       
}

【讨论】:

    【解决方案2】:

    如果这些表不相关,则只需 2 个查询即可:

    foreach ($tests as $test) {
        $products[] = [
            'name' => $tests->name,
            'wage' => $tests->wage
        ];     
    
        $otherData[] = [
            'sex' => $tests->sex,
            'age' => $tests->age
        ];
    }
    
    Products::insert($products);
    OtherModel::insert($otherData);
    

    如果这些模型相关,您需要创建 51 个查询而不是 2 个(仍然优于 100 个查询):

    foreach ($tests as $test) {
        $productId = Products::insertGetId([
            'name' => $tests->name,
            'wage' => $tests->wage,
        ]);     
    
        $otherData[] = [
            'sex' => $tests->sex,
            'age' => $tests->age,
            'product_id' => $productId
        ];
    }
    
    OtherModel::insert($otherData);
    

    如果这些模型是相关的,而您仍然希望只通过几个查询来完成此操作,则可以使用事务:

    DB::transaction(function () {
        $productId = (int)DB::table('products')->orderBy('id', 'desc')->value('id');
        foreach ($tests as $test) {
            $productId++;
    
            $products[] = [
                'name' => $tests->name,
                'wage' => $tests->wage
            ];     
    
            $otherData[] = [
                'sex' => $tests->sex,
                'age' => $tests->age,
                'product_id' => $productId
            ];
        }
    
        Products::insert($products);
        OtherModel::insert($otherData);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2010-11-02
      • 2014-08-30
      相关资源
      最近更新 更多