Phoenix
Phoenix

Reputation: 1075

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

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?

Upvotes: 3

Views: 5921

Answers (3)

mikeyb
mikeyb

Reputation: 93

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.

Upvotes: 4

Jonathan
Jonathan

Reputation: 11494

Have you tried updateOrCreate(array $attributes, array $values = [])?

As long as you use a table that has an auto-increment id column, you can use your Model::updateOrCreate() with the first argument as an associative array consisting of the attributes you are looking for, and the second argument as an associative array with any new values.

See the method definition for updateOrCreate.

Upvotes: 0

Hakob Hakobyan
Hakob Hakobyan

Reputation: 1131

From Laravel Documentation (see here last part) There are two methods in Laravel:

Other Creation Methods

There are two other methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew. The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:

// Retrieve the flight by the attributes, or create it if it doesn't exist...

$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve the flight by the attributes, or instantiate a new instance...

$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

Upvotes: 0

Related Questions