如何更新 laravel 中 table 的 json 列

How to update a json column of a table in laravel

我在帐户的玩具列中有以下 JSON 个值 table

{
   "truck":{
      "qty":10,
      "price":53
   },
   "doll":{
      "qty":15,
      "price":15
   }
}

现在我想为此添加新值 {"animals":{"qty":1,"price":4},"stickers":{"qty":12,"price":12}}。我试过下面的方法

    $new_toys = [
       'animals'  => ['qty' => 1, 'price' => 4],
       'stickers' => ['qty' => 12, 'price' => 12]
    ];
    $old_tyoys = $account->toys;
    array_push($old_tyoys, $new_toys);
    $account->toys = $old_tyoys;
    $account->save();

但这会将列更新如下

{
   "truck":{
      "qty":10,
      "price":53
   },
   "doll":{
      "qty":15,
      "price":15
   },
   "0":{
      "animals":{
         "qty":1,
         "price":4
      },
      "stickers":{
         "qty":12,
         "price":12
      }
   }
}

但我想要如下

{
   "truck":{
      "qty":10,
      "price":53
   },
   "doll":{
      "qty":15,
      "price":15
   },
   "animals":{
      "qty":1,
      "price":4
   },
   "stickers":{
      "qty":12,
      "price":12
   }
}

我需要在代码中更改什么?谢谢

那是因为您正在使用 array_push 来聚合两个对象,并且它在内部将您的第二个参数添加为分配给数字索引 0 的值。尝试使用 array_merge.

array_push($old_tyoys, $new_toys);替换为collect($account->toys)->merge($new_toys)->all();

所以你的方法代码会变成

$new_toys = [
       'animals'  => ['qty' => 1, 'price' => 4],
       'stickers' => ['qty' => 12, 'price' => 12]
    ];

$merged = collect((array)$account->toys)->merge(new_toys)->all();

//Or

$merged = array_merge((array) $account->toys, $new_toys);

$account->toys = $merged;
$account->save();