Laravel JSON字段无法更新或更新或创建(如果不存在) [英] Laravel JSON field can't update or updateOrCreate if not exist
问题描述
使用Laravel 5.6.我有一个称为metas
的JSON字段,插入和更新可按预期工作,但有1件事:如果metas
中不存在该字段,则不会在update或updateOrdCreate方法上创建该字段.存在的字段更新没有问题.
Using Laravel 5.6. I have JSON field called metas
Inserting and Updating works as expected except 1 thing: if field doesn't exist in metas
it will not be created on update or updateOrdCreate methods. Fields that exist updating without problem.
以下是示例metas
内容:
{
"date": "2018-09-17",
"name": "r08"
}
我可以更新日期"和名称",但是在某些情况下,我需要为示例距离"添加新字段,但我不能这样做:
I can update "date" and "name", but there will be some situations where I need to add new field for excample "distance", I can't do this:
Registries::where('id', $registry_id)->update([
'metas->distance' => '200km'
]);
也尝试过:
Registries::where('id', $registry_id)->updateOrCreate([
'metas->distance' => '200km'
]);
没有错误.
推荐答案
Laravel JSON casting only creates JSON accessor (deserializer) and mutator (serializer) for you:
在该属性上添加
array
强制转换后,当您在Eloquent模型上访问该属性时,该属性会自动反序列化到PHP数组.
Adding the
array
cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model.
一旦定义了cast
,您就可以访问该属性,它将自动从JSON反序列化为PHP数组.当您设置属性的值时,给定的数组将自动序列化回JSON以进行存储
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/数组字段的唯一方法是覆盖其值:
So the only way to update a JSON/array field is by overriding its value:
$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字段无法更新或更新或创建(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!