如何在 laravel 中更新表的 json 列

问题描述 投票:0回答:2

帐户表的玩具列中有以下 JSON 值

{
   "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
   }
}

我需要更改代码中的哪些内容?谢谢

php mysql arrays json laravel
2个回答
2
投票

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();

0
投票

那是因为您使用

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

© www.soinside.com 2019 - 2024. All rights reserved.