LoginSignup
0
0

More than 1 year has passed since last update.

LaravelでCollection型のデータを作ってバルクインサートする

Posted at

それなりの量のデータをインサートする場合、バルクインサートをしたほうが早いです。

例えば下記のようなデータがある場合を考えます。

$posts = new Collection();
for ( $i = 0; $i < 1000000; $i++ ) {
   /** @var Post $row */
   $post                  = new Post();
   $post->title   = 'Hello';
   $post->content = 'Good day';
}

下記のように都度save()を走らせるとかなり遅いです。

foreach($posts as $post) {
  $post->save();
}

DB::insert() メソッドを使うとバルクインサート(一括インサート)となるため早いです。

Post::insert($posts->toArray());

下記の記事を参考にするとInsert文を確認できます。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0