4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel5.2でON DUPLICATE KEY UPDATEを実行する

Last updated at Posted at 2017-02-21

個人のメモも兼ねて投稿します。

LaravelでSQLの「ON DUPLICATE KEY UPDATE(InsertOrUpdate)」を実施しようとした際、Laravelに搭載されているクエリービルダーには無かったので以下に記載します。(実はあるかもしれませんが)

「ON DUPLICATE KEY UPDATE」を使用する方法

$columns = "`column1`, `column2`";
$values = "'column1', 'column2'";
$updates = "`column1` = 'column3'";

// SQL文生成
$sql = "INSERT INTO `table` ({$columns}) VALUES ({$values}) ON DUPLICATE KEY UPDATE {$updates}";

// SQL実行
DB::statement($sql);

検証はしておりませんが、恐らく他のLaravelのバージョンでも使用可能だと思います。
もっと良いやり方があるなら知りたいです・・・・。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?