首页 > 解决方案 > Laravel:json 编码在数据库更新中返回空

问题描述

当我在 laravel 的更新查询生成器中使用 json_encode 时,它​​返回空。我试过的代码是这样的:

    DB::table('catalog_product')->update([
        'reference' => json_encode(['data' =>DB::raw('external_barcode')]),
    ]);

我该怎么做呢?

标签: jsonlaravel

解决方案


正如我所说,您将 PHP 函数与 MYSQL 值混合在一起。

或者你使用 PHP 方式:

$products = CatalogProduct::get();

foreach ($products as $product) {
   $product->reference = json_encode(['data' => $product->external_barcode]);
   $product->save();
}

或使用 MYSQL :

DB::table('catalog_product')->update([
    'reference' => DB::raw('JSON_OBJECT("data", external_barcode)'),
]);

推荐阅读