LoginSignup
2
4

More than 5 years have passed since last update.

Laravel 5.1 Seeder における DB::table()->truncate v.s. updateOrCreate

Last updated at Posted at 2017-03-09

どちらが良いのだろうか。

どちらも冪等性が保証される

DB::table('table')->truncate ()

CategoryTableSeeder.php
// 外部キー制約を一時的に無効にする
DB::statement('SET FOREIGN_KEY_CHECKS=0;');

DB::table('categories')->truncate();

$category = [
    'id' => 1,
    'name' => 'IT',
];

DB::table('categories')->insert($category);

DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  • こっちの方が多数派?
  • 一時的にデータが消えるので、一瞬エラーは出そう

updateOrCreate

CategoryTableSeeder.php
$category = [
    'id' => 1,
    'name' => 'IT',
];
Category::updateOrCreate(['id' => $attributes['id']], $attributes);
  • 一時的に消さなくて良い
  • モデルに $fillable を設定する必要がある
  • 多分性能(処理速度)は悪い
2
4
2

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
2
4