Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write "on duplicate key update" for Laravel 5.2 eloquent model?

Tags:

php

laravel

I have a table, it's unique key is app_id + channel_id but it doesn't have primary key.

I want to use on duplicated key update statement to insert/update a last_update_time field in Laravel eloquent model, I found updateOrCreate method but it's not recognized in my project, how should I write my model?

like image 566
Phoenix Avatar asked Jan 20 '26 08:01

Phoenix


1 Answers

DB::statement("INSERT INTO `table_name`(`col_name_1`, `col_name_2`) VALUES (?, ?) ON DUPLICATE KEY UPDATE col_name_1= VALUES (col_name_1)", [val_1, val_2]);

Laravel allows for raw database statements with DB::statment($query, $bindings = []).

One thing to make sure of, the second argument must be an indexed array and not an associative. If it is associative it will throw a general SQL exception.

like image 194
mikeyb Avatar answered Jan 23 '26 08:01

mikeyb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!