如何在onces上将多行保存到多个数据库表

时间:2018-01-15 10:46:44

标签: laravel eloquent

例如我有" id,姓名,工资,性别,年龄"列。

  • 1,John,3,M,30
  • 2,Angela,5,F,26

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

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

   }
  Products::insert($data);

这是正确的方法吗?我无法弄清楚正确的方法。

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:0)

您可以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();                       
}