【问题标题】:Laravel eloquent update JSON column some fields without overriding everything elseLaravel 雄辩地更新 JSON 列一些字段而不覆盖其他所有内容
【发布时间】:2020-07-18 11:08:09
【问题描述】:

我们正在尝试使用JSON datatypes 来存储Profile 动态数据,并且不知道要添加到模型中fillable 属性的所有硬编码字段名称。如何设置(insert如果密钥不存在|update如果密钥存在)只有一个键,而不是全部?

例如,如果我们只想更新 age 并且我们使用:

$model = Profile::find($profile_id);
$model->options = json_encode(['age' => '21']);
$model->save();

此解决方案不是一个很好的选择,因为它会覆盖其他所有内容。 我们如何在不更改其他字段(JSON 键)的情况下仅设置所需字段?

【问题讨论】:

标签: eloquent mysql-json


【解决方案1】:

纯mysql中的解决方案是:

UPDATE `profiles`
SET `data` = JSON_SET(
    `data` ,
    '$.age' ,
    '21'
)
WHERE
    `id` = 1;

JSON_SET 函数将添加如果未找到该属性,否则替换它。 read more here

但在 Laravel 中,你应该设置 Model $guarded 属性,并删除 $fillable(或留空),然后除 guarded 之外的所有内容都将是 fillable

那么你可以使用:

Profile::find($profile_id)->update([
   'data->age' => 21,
   'data->gender' => 'male',
]);

there are good experiences here

您也可以使用以下代码作为@Jonas Staudenmeir mentioned

DB::table('...') with Profile::query()

https://laravel.com/docs/7.x/queries#updating-json-columns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2022-12-09
    • 1970-01-01
    • 2018-01-03
    • 2020-05-30
    • 2021-06-01
    • 2017-03-05
    • 2014-08-03
    相关资源
    最近更新 更多