在 Laravel 5.2 中批量插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41871287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:12:31  来源:igfitidea点击:

Batch insert in Laravel 5.2

laravellaravel-5.2batch-insert

提问by Irfan Ali

I am using a API's with lot's of calculation almost 100 database fields at the end with a big Foreach loop.

我正在使用一个 API 进行大量计算,最后有一个大的 Foreach 循环,几乎有 100 个数据库字段。

In every iteration i insert data in database. I want to insert data in once at the end (Batch Insert like in CodeIgniter).

在每次迭代中,我都会在数据库中插入数据。我想在最后插入一次数据(如 CodeIgniter 中的批量插入)。

Any body have idea how to insert all data at the end of iteration. instead of every iteration it insert row in database.

任何机构都知道如何在迭代结束时插入所有数据。它在数据库中插入行而不是每次迭代。

I want to insert data at the end of loop. Any help or idea appreciated.

我想在循环结束时插入数据。任何帮助或想法表示赞赏。

回答by Alexey Mezenin

Use insert()method for bulk insertion. First, build an array with this structure:

insert()批量插入的使用方法。首先,用这个结构构建一个数组:

$data = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Maria', 'age' => 31],
    ['name' => 'Julia', 'age' => 55],
];

Then insert the data using Eloquent model:

然后使用 Eloquent 模型插入数据:

Model::insert($data);

Or using query builder:

或者使用查询构建器:

DB::table('table_name')->insert($data);