使用 Laravel 5.6。我有一个名为 metas
的 JSON 字段,插入和更新按预期工作,除了一件事:如果 metas
中不存在字段,则不会在 update 或 updateOrdCreate 方法上创建它。存在的字段更新没有问题。
这是示例元
内容:
{
"date": "2018-09-17",
"name": "r08"
}
我可以更新“日期”和“名称”,但在某些情况下我需要添加新字段,例如“距离”,我不能这样做:
Registries::where('id', $registry_id)->update([
'metas->distance' => '200km'
]);
还尝试过:
Registries::where('id', $registry_id)->updateOrCreate([
'metas->distance' => '200km'
]);
没有错误。
最佳答案
Laravel JSON casting仅为您创建 JSON 访问器(反序列化器)和更改器(mutator)(序列化器):
Adding the
array
cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model.Once the
cast
is defined, you may access the attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the attribute, the given array will automatically be serialized back into JSON for storage
因此更新 JSON/数组字段的唯一方法是覆盖其值:
$registry = Registries::find($registry_id);
$registry->metas['distance'] = '200km';
$registry->save();
或
Registries::updateOrCreate(
['id', $registry_id],
['metas' => json_encode([
'date' => '2018-09-17',
'name'=> 'r08',
'distance' => '200km',
])]
);
关于Laravel JSON 字段如果不存在则无法更新或 updateOrCreate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52607995/