Laravel JSON 字段如果不存在则无法更新或 updateOrCreate

标签 laravel laravel-5

使用 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/

相关文章:

Laravel Eloquent 增量不更新时间戳

php - 在 Laravel PHP 框架中找不到 PGSQL 驱动程序

php - Laravel 子域在重定向时丢失 session

php - (1/1) MethodNotAllowedHttpException

php - 使用 laravelcollective/html 组件比使用常规的简单 HTML 标签构建 View 元素有什么优势?

php - 单元测试 Laravel 密码重置电子邮件 - 可邮寄未排队

javascript - Uncaught ReferenceError : require is not defined at require ('./bootstrap' ) Laravel Mix

php - Laravel 5 请求 - 如何显示单独的验证错误

jquery - 模态隐藏后更改CSS样式

php - Laravel - 如何在用户未通过身份验证时重定向到所需页面