【问题标题】:Laravel 8 upsert with DB::Raw queryLaravel 8 upsert 与 DB::Raw 查询
【发布时间】:2021-03-02 03:52:52
【问题描述】:

我希望使用 Laravel 8 的原生 upsert 功能来导入一批产品。当使用 https://github.com/staudenmeir/laravel-upsert 包时,我可以例如当数据库模型中不存在时,只需使用以下内容更新图像:

Product::upsert(
    $values,
    $target,
    [
        'image' => DB::raw("if(`image` is null, values(`image`), `image`)"),
        // TODO: Add the other columns that should be updated.
    ]
);

但是,这似乎不适用于 Laravel 8 的 upsert 版本。关于如何做到这一点的任何想法?

更新: 我目前正在尝试的代码是:

ShopProduct::upsert(
    $productArray,
    ['productcode'],
    [
       'image' => DB::raw("if(`image` is null, values(`image`), `image`)"),
    ]);

我得到的错误:

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")

【问题讨论】:

  • 您查看查询了吗? DB::enableQueryLog(); Product::upsert(...); dd(DB::getQueryLog());
  • @Anticom 由于错误,查询不会记录。我已经用额外的信息更新了帖子。
  • 您在尝试使用之前查看过the documentation for the function 吗?没有任何迹象表明你可以做任何你想做的事情。 “该方法的第三个也是最后一个参数是一个列数组,如果数据库中已经存在匹配记录,则应该更新这些列。”
  • 是的,我做了@miken32,但由于他们已经实施和调整了github.com/staudenmeir/laravel-upsert,我有点希望这能继续工作。我想这是一个不 :(

标签: php laravel upsert laravel-8


【解决方案1】:

我用这个功能让事情变得更简单:

protected function coalesce(array $columnNames):array{
        $columns = [];
        foreach($columnNames as $value){
            $columns["{$value}"] = DB::raw("COALESCE(`{$value}`,values(`{$value}`))");
        }
        return $columns;
    }


ShopProduct::upsert(
    $productArray,
    ['productcode'],
    $this->coalesce(['image]));

Coalesce 将采用列的值或传递的值,具体取决于是否为空

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 2017-06-14
    • 2018-01-31
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2018-10-24
    • 2020-06-10
    相关资源
    最近更新 更多