Laravel中如何更新MySQL JSON类型列内指定对象的数据?
在Laravel中更新JSON数组指定对象的字段
假设你的JSON列名为flats(请替换为实际列名),表名为properties,以下是两种实用实现方式:
方法一:直接通过MySQL JSON函数更新(推荐,性能更高)
利用MySQL原生JSON函数,直接在数据库层面完成更新,无需取出整个JSON数据集:
$targetFlatName = '1B'; $newCustomerId = 5; // 替换为你要设置的customer ID DB::table('properties') ->whereRaw( 'JSON_SEARCH(flats, "one", ?) IS NOT NULL', [$targetFlatName] ) ->update([ 'flats' => DB::raw( 'JSON_REPLACE( flats, REPLACE(JSON_SEARCH(flats, "one", ?), ".flat_name", ".customer"), ? )', [$targetFlatName, $newCustomerId] ) ]);
逻辑说明:
JSON_SEARCH(flats, "one", "1B"):在flats数组中定位第一个flat_name为1B的字段,返回其路径(例如$[1].flat_name)REPLACE(...):将路径中的.flat_name替换为.customer,得到要更新的目标字段路径(例如$[1].customer)JSON_REPLACE:根据生成的路径替换对应字段的值
方法二:PHP层面修改后重新保存
适合JSON数据量较小的场景,先取出数据修改再写入:
// 假设你有对应的Eloquent模型Property $property = Property::find($propertyId); // 替换为实际的记录ID // 将JSON列转为PHP数组(若模型未配置自动转换,需先配置$casts) $flats = $property->flats; // 遍历数组找到目标对象并更新 foreach ($flats as &$flat) { if ($flat['flat_name'] === '1B') { $flat['customer'] = $newCustomerId; break; // 找到目标后终止循环 } } // 保存修改后的数组 $property->flats = $flats; $property->save();
额外配置:
如果模型未自动将JSON列转为数组,需在Property模型中添加$casts属性:
protected $casts = [ 'flats' => 'array', ];
内容的提问来源于stack exchange,提问作者Md Amranur Rahman
相关产品推荐
相关产品推荐

