John Davidson

php - Laravel 8 upsert with DB::Raw query


I am looking to use Laravel 8's native upsert function to import a batch of products. When using the package I could e.g. just use the following to update an image when not existing in the DB model:

'image' => DB::raw("if(`image` is null, values(`image`), `image`)"),
// TODO: Add the other columns that should be updated.

However, this does not seem to work in Laravel 8's version of upsert. Any ideas on how I can do this?

The code I am trying currently is:

'image' => DB::raw("if(`image` is null, values(`image`), `image`)"),

And the error I get:

SQLSTATE[HY000]: General error: 1 near "values": syntax error (SQL: insert into "shop_products" ("created_at", "image", "name", "productcode", "slug", "updated_at") values (2020-11-18 21:52:03, /var/folders/y_/whnvprxj6hx514qmgwj_lb740000gn/T/cf46d09ad8845c9ff742a9045090d252.png, tempora, 6011295759374531, tempora, 2020-11-18 21:52:03), (2020-11-18 21:52:03, /var/folders/y_/whnvprxj6hx514qmgwj_lb740000gn/T/d0842fcf4ea08a4dab9f82e9456fdd36.png, qui, 4024007178334, qui, 2020-11-18 21:52:03) on conflict ("productcode") do update set "image" = if(`image` is null, values(`image`), `image`), "updated_at" = "excluded"."updated_at")

My Answer:
DB::raw('IFNULL(VALUES(image), image)') ]);However, with Laravel 8's native upsert function, I am not sure how to achieve the same result with a DB::Raw query. Can anyone provide an example of how to use a DB::Raw query in Laravel 8's upsert function to update a specific column only if it does not exist in the database model?

Rate this post

3 of 5 based on 8424 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us