LoginSignup
4
2

More than 5 years have passed since last update.

Laravel のクエリビルダで UPSERT を実装する

Last updated at Posted at 2018-11-20

Laravel のクエリビルダで UPSERT を実装する

マイグレーションファイル内で UPSERT を使いたかったが、なさげなので自分で実装した。

public function up()
{
    // 多次元配列で UPSERT データを取得
    $seeds = $this->getSeedData();
    foreach ($seeds as $seed) {
        $record = \DB::connection('DB名')->table('テーブル名')->where('id', $seed['id']);
        $record->exists() ? $record->update($seed) : $record->insert($seed);
    }
}

private function getSeedData()
{
    return [
        ['id' => 1, 'memo' => '腰が'],
        ['id' => 2, 'memo' => '痛い'],
    ];
}

Model ファイル内なら

Eloquent でこういうことができるらしい

// User モデル で id = 1 があったら第二引数で UPDATE、なければ第二引数で INSERT
App\User::updateOrCreate(['id' => 1], ['hoge' => 1]);
4
2
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
4
2