Laravel 5.1 Create or Update on Duplicate

前端 未结 6 953
悲哀的现实
悲哀的现实 2020-12-03 01:29

In Laravel 5.1, for MySQL insert, I want to see if the record already exists and update on duplicate or create new if none exists.

I have already searched SO where t

6条回答
  •  甜味超标
    2020-12-03 01:53

    I am answering to this question cause I can't find any answer related to ON DUPLICATE KEY UPDATE, although I am using Laravel 5.4. If you look at the updateOrCreate method in the Laravel's core code, you will see after all Laravel is using 2 different queries: one for update and another one for create. Because of this, sometimes you can get duplicated data in the DB. So in some cases it can be useful to write this kind of raw query:

    DB::statement("INSERT INTO table_name (col_1, col_2) VALUES (?, ?) ON DUPLICATE KEY UPDATE col_1 = col_1 + 1", ([val_1, val_2]));

    Hope it can be useful for someone.

提交回复
热议问题