John Davidson

php - Laravel 8 upsert with DB::Raw query

0 comments
Message:


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


Product::upsert(
$values,
$target,
[
'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?


Update:
The code I am trying currently is:


ShopProduct::upsert(
$productArray,
['productcode'],
[
'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

Comments




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