Laravel 8整数ID插入时带方括号导致SQL查询失败问题
Laravel Eloquent插入时ID被自动添加方括号的问题解决
问题描述
在Laravel框架中使用Eloquent创建Category记录后,获取到的新记录ID($categoryId)打印显示为整数类型,但将其赋值给Product模型的category_id字段并执行插入时,该值被自动加上方括号(如[1]),导致SQL插入报错。尝试去除方括号时,系统提示该值已是整数,无法定位问题根源。
相关代码
$newCategory = new Category; $newCategory->short_desc = $category; $newCategory->save(); $categoryId = $newCategory->id; $newProduct = new Product; $newProduct->name = $product_name; $newProduct->category_id = $categoryId; $newProduct->save(); $productId = $newProduct->id;
错误信息
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '[1]' for column 'category_id' at row 1 (SQL: insert into `products` (`name`, `description`, `category_id`, `container_id`, `user_id`, `updated_at`, `created_at`) values (Razer Blade 16, AMD \" 10, [1], [2], 1, 2022-09-14 15:24:36, 2022-09-14 15:24:36))
迁移文件
Product表迁移
Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name', '255')->index(); $table->text('description'); $table->unsignedBigInteger('category_id')->nullable()->index(); $table->unsignedBigInteger('container_id')->nullable()->index(); $table->unsignedBigInteger('user_id')->index(); $table->timestamps(); $table->softDeletes(); $table->foreign('category_id')->references('id')->on('categories'); $table->foreign('container_id')->references('id')->on('containers'); $table->foreign('user_id')->references('id')->on('users'); });
Category表迁移
Schema::create('categories', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('short_desc', '255'); $table->text('description'); $table->timestamps(); $table->softDeletes(); });
解决方法
1. 检查Product模型的$casts属性
最可能的原因是Product模型中错误地将category_id字段设置为了数组类型的转换。打开Product模型,查看$casts配置:
// 错误示例 protected $casts = [ 'category_id' => 'array', ];
Eloquent会自动将数组类型的字段转成JSON格式存储,导致插入时出现方括号。只需将其修改为正确的整数类型:
// 正确配置 protected $casts = [ 'category_id' => 'integer', ];
如果不需要类型转换,直接移除该字段的配置即可。
2. 强制类型转换(临时解决)
如果暂时无法修改模型配置,可以在赋值时强制将ID转为整数:
$newProduct->category_id = (int)$categoryId;
但建议优先排查模型的$casts配置,这才是问题的根源。
3. 检查请求参数或变量类型
确认$category等变量不是数组类型,避免在创建Category时间接影响后续ID的处理逻辑,但从现有代码来看,这种可能性较低。
内容的提问来源于stack exchange,提问作者Kai Hiwatari
相关产品推荐
相关产品推荐

