0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Eloquent::createとDB::insertを書いたときに実行されるSQLについて復習。

結論

  1. Eloquent::create() → 1回呼ぶごとに1つのINSERTが実行される
  2. DB::insert() → 配列で渡すと1回のクエリで複数行のINSERTが実行される

Eloquentの create() の動作について

Eloquentの Model::create() を使うと、1回の呼び出しごとに1行ずつINSERT文が発行される。

User::create([
    'name' => 'Alice',
    'email' => 'alice@example.com',
]);

このコードは、次のような1行だけのINSERTクエリを発行します。

insert into `users` (`name`, `email`, `created_at`, `updated_at`) values ('Alice', 'alice@example.com', '2025-05-22 12:00:00', '2025-05-22 12:00:00');

DB::insert() の動作について

Eloquentの create() は「1レコードずつ」扱う。
大量データを一括でINSERTしたいときは、クエリビルダの DB::table()->insert() を使うのが適している。

DB::table('users')->insert([
    ['name' => 'Alice', 'email' => 'alice@example.com'],
    ['name' => 'Bob', 'email' => 'bob@example.com'],
]);

このコードは、次のようなINSERTクエリを発行します。

insert into `users` (`name`, `email`) values 
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com');

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?