You need to enable JavaScript to run this app. 如何将JSON格式数据存入数据库?Laravel控制器数据插入问题
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON格式数据存入数据库?Laravel控制器数据插入问题

解决步骤

你当前的核心问题有两个:

  • 待入库的原始数据是两个拼接的独立JSON对象,不属于合法的JSON数组,直接解析会报错
  • 遍历逻辑中没有将解析后的JSON字段映射到插入数组的对应位置,且缺失的字段没有做兜底处理

1. 预处理原始JSON字符串

如果$request->get('set_components')返回的是类似{"category_id":"1",...}{"category_id":"3",...}的字符串,先给它包裹一层方括号转成合法的JSON数组格式,再解析为PHP关联数组:

// 先拿到原始的set_components值,可dd()确认实际类型
$set_components_str = $request->get('set_components');

// 如果是字符串则做格式修正
if (is_string($set_components_str)) {
    // 前后加方括号,将拼接的两个对象转换为数组元素
    $json_arr_str = '[' . $set_components_str . ']';
    // 解析为关联数组,true参数表示返回关联数组而非对象
    $set_components = json_decode($json_arr_str, true);
} else {
    // 如果本身已经是合法数组则直接使用
    $set_components = $set_components_str;
}

// 兜底校验:解析失败或为空时直接返回错误
if (empty($set_components) || !is_array($set_components)) {
    return response()->json(['success' => false, 'msg' => '数据格式错误'], 400);
}

2. 修正遍历映射逻辑

遍历数组时需要注意:

  • 缺失的字段(比如第一条没有subtopic_id、第二条没有scenario_id)要用??运算符给默认值(一般给null,对应数据库的可空字段)
  • 注意字段名对应:JSON里的nonscoring要映射到你数据库的non_scoring字段

修正后的完整代码:

public function store(Request $request)
{
    // 预处理原始数据
    $set_components_str = $request->get('set_components');
    if (is_string($set_components_str)) {
        $json_arr_str = '[' . $set_components_str . ']';
        $set_components = json_decode($json_arr_str, true);
    } else {
        $set_components = $set_components_str;
    }

    // 数据合法性校验
    if (empty($set_components) || !is_array($set_components)) {
        return response()->json(['success' => false, 'msg' => '待入库数据格式非法'], 400);
    }

    $components = [];
    $user_id = Auth::user()->id;
    foreach ($set_components as $item) {
        $components[] = [
            'set_id' => 1,
            'category_id' => $item['category_id'] ?? null,
            'topic_id' => $item['topic_id'] ?? null,
            // 缺失的字段自动兜底为null
            'subtopic_id' => $item['subtopic_id'] ?? null,
            'scenario_id' => $item['scenario_id'] ?? null,
            'scoring' => $item['scoring'] ?? 0,
            // JSON字段nonscoring对应数据库字段non_scoring
            'non_scoring' => $item['nonscoring'] ?? 0,
            'created_by' => $user_id,
            // 批量插入时如果数据库要求时间戳非空,需手动补充
            'created_at' => now(),
            'updated_at' => now(),
        ];
    }

    // 批量插入数据
    Set_component::insert($components);

    return response()->json([
        'success' => true,
        'data' => $components
    ]);
}

补充提醒

  • 批量插入的字段值类型要和数据库字段类型匹配,比如JSON里拿到的都是字符串,若数据库是int类型,要手动转成int:(int)($item['category_id'] ?? null)
  • 如果数据库字段有非空约束,兜底的默认值要符合非空要求,不能随意给null
  • 如果原始数据本身就是前端传的合法JSON数组,上述字符串处理逻辑可以跳过,先dd($set_components_str);确认实际数据格式再调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 00:15:03