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

Laravel单查询批量插入多条记录失败,报General error:1364错误

Laravel批量插入Challen记录报错解决方案

报错信息

常规错误:1364 字段'challen_student_id'没有默认值(SQL语句:insert into challens (updated_at, created_at) values (2022-10-04 08:53:41, 2022-10-04 08:53:41))

问题代码

$students = Student::all('id');
$collection = collect($students)->map(function ($student) use($request) {
$collect = collect(['challen_student_id', 'challen_month', 'challen_due_date', 'challen_fine', 'challen_exam_fees', 'challen_status']);
    return $collect->combine([$student->id, $request->item['challen_month'], $request->item['challen_due_date'], $request->item['challen_fine'], $request->item['challen_exam_fee'], 'pending'])->toArray();
});
    
// print_r($collection->toarray());
// exit;
Challen::create($collection->toArray());

输出结果

Array (
    [0] => Array (
        [challen_student_id] => 1
        [challen_month] => 
        [challen_due_date] => 
        [challen_fine] => 
        [challen_exam_fee] => 
        [challen_status] => pending
    )
)

解决步骤

1. 替换批量插入方法

create()是Laravel用于单条记录插入的方法,仅接收一维数组。你生成的是二维数组(多条记录),需要改用insert()方法实现批量插入:

// 替换原有的Challen::create(...)
Challen::insert($collection->toArray());

2. 检查模型可赋值字段

确保Challen模型中已声明允许批量赋值的字段,否则Laravel会过滤未授权字段,导致插入字段缺失:

class Challen extends Model
{
    protected $fillable = [
        'challen_student_id',
        'challen_month',
        'challen_due_date',
        'challen_fine',
        'challen_exam_fees', // 注意:代码中字段名是challen_exam_fees,但输出是challen_exam_fee,需和数据库字段保持一致
        'challen_status'
    ];
}

3. 处理空值问题

从输出结果看,challen_month等字段为空。如果数据库中这些字段不允许为空,需先校验请求数据确保必填字段有值,或者修改数据库表结构允许这些字段为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:40:40