You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在入库前编辑JSON列?预订时需将登录用户名加入JSON类型comment列

正确编辑JSON类型comment列并添加登录用户名的方法

1. 先确保模型配置正确

在你的Booking模型中,添加$casts属性将comment字段转换为数组类型,Laravel会自动完成JSON与数组的互转:

class Booking extends Model
{
    protected $casts = [
        'comment' => 'array',
        // 其他字段的类型转换...
    ];
}

2. 处理comment字段的两种常见场景

场景1:原comment是普通字符串(如示例中的"hiii")

如果想把原评论内容和用户名组合成结构化JSON,直接构建数组即可:

// 获取登录用户的用户名
$username = auth()->user()->name;

// 覆盖原comment为包含用户名的数组
$booking->comment = [
    'message' => $booking->comment, // 保留原评论内容
    'username' => $username
];

// 保存到数据库
$booking->save();

场景2:原comment已经是JSON对象(数组形式)

如果原comment本身就是结构化JSON,直接添加用户名字段即可:

$username = auth()->user()->name;

// 直接向数组添加新字段
$booking->comment['username'] = $username;

$booking->save();

3. 兼容空值或混合类型的通用写法

如果comment可能是空值、字符串或数组,用以下代码兼容所有情况:

$username = auth()->user()->name;
$comment = $booking->comment;

if (empty($comment)) {
    // 空值时直接设置用户名
    $booking->comment = ['username' => $username];
} elseif (is_string($comment)) {
    // 字符串时转为结构化数组
    $booking->comment = [
        'message' => $comment,
        'username' => $username
    ];
} else {
    // 已为数组时添加字段
    $booking->comment['username'] = $username;
}

$booking->save();

原代码的问题说明

$booking['comment']->setAttribute()是错误用法,$booking['comment']是字段值(字符串/数组),并非模型实例,setAttribute()是模型的方法,不能直接用在字段值上。

内容的提问来源于stack exchange,提问作者Shubham Rana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:15:16