php 使用 Laravel 一次插入多条记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39113682/
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
Insert Multiple Records At Once With Laravel
提问by Steve
I am inserting the data to the rows one by one, but I have heard somewhere that it requires much time if there are many data to insert. So what are the ways of inserting them all at once?
我正在将数据逐行插入,但我在某处听说如果要插入的数据很多,则需要很长时间。那么一次性插入的方法有哪些呢?
public function add(Request $request)
{
if ($request->ajax()) {
$books = $request->books;
foreach ($books as $book) {
if (!empty($book)) {
$add = new Book;
$add->name = $book;
$add->user_id = Auth::user()->id;
$add->save();
}
}
}
}
回答by Hamelraj
public function add(Request $request)
{
if($request->ajax())
{
$books=$request->books;
$data = array();
foreach($books as $book)
{
if(!empty($book))
{
$data[] =[
'name' => $book,
'user_id' => Auth::id(),
];
}}
Book::insert($data);
<!--DB::table('books')->insert($data);-->
}}
make sure imported use Illuminate\Support\Facades\Auth;
确保进口 use Illuminate\Support\Facades\Auth;
回答by Qevo
Insert multiple records using the Model
使用模型插入多条记录
As others have pointed out, using the Query Builder is the only way to insert multiple records at a time. Fortunately Laravel and the Eloquent ORM are coupled in many useful ways. This coupling allows you to use a Model to get a Query Builder instance that is set for that Model.
正如其他人指出的那样,使用查询生成器是一次插入多条记录的唯一方法。幸运的是,Laravel 和 Eloquent ORM 以许多有用的方式耦合。这种耦合允许您使用模型来获取为该模型设置的查询生成器实例。
// use Auth;
// use Carbon;
// use App\Book;
public function add(Request $request)
{
if($request->ajax())
{
// Submitted books
$books = $request->books;
// Book records to be saved
$book_records = [];
// Add needed information to book records
foreach($books as $book)
{
if(! empty($book))
{
// Get the current time
$now = Carbon::now();
// Formulate record that will be saved
$book_records[] = [
'name' => $book,
'user_id' => Auth::user()->id,
'updated_at' => $now, // remove if not using timestamps
'created_at' => $now // remove if not using timestamps
];
}
}
// Insert book records
Book::insert($book_records);
}
}
回答by Anushan W
You should be able to do something like below:
您应该能够执行以下操作:
DB::table('users')->insert([
['email' => '[email protected]', 'votes' => 0],
['email' => '[email protected]', 'votes' => 0]
]);
Put all the values you want to insert in to an array and then pass it to the insert function.
将所有要插入的值放入一个数组中,然后将其传递给 insert 函数。
回答by Bogdan Koliesnik
If you need Eloquent model events- there is no other way to insert multiple models. In other way - check Anushan Wanswer
如果您需要 Eloquent模型事件- 没有其他方法可以插入多个模型。以其他方式 - 检查Anushan W 的答案