TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
搜索到 1 篇与 的结果
2025-08-14

解决Laravel迁移中外键重复列错误:foreignId的正确使用

解决Laravel迁移中外键重复列错误:foreignId的正确使用
一、为什么会出现「外键重复列」错误?当你在 Laravel 迁移中看到类似以下报错:bash SQLSTATE[42701]: Duplicate column: 7 ERROR: column "user_id" specified more than once这通常是因为错误地混合使用了多种外键定义方式。例如同时使用:php $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users');和php $table->foreignId('user_id')->constrained();这两种写法实际上会生成重复的列定义,因为 foreignId() 已经包含了创建字段的逻辑。二、foreignId 的设计哲学Laravel 8+ 引入的 foreignId 方法是一个语法糖,它封装了以下操作: 1. 创建 unsignedBigInteger 列 2. 自动关联主表的主键(默认 id) 3. 支持链式调用定义约束...
2025年08月14日
40 阅读
0 评论