Laravel外键声明报错解决:users_id列不存在问题排查
解决Laravel迁移中外键关联报错问题
问题场景
在Laravel中创建users和drawings两张表并建立外键关联时,执行php artisan migrate命令报错,其他字段创建正常,仅外键部分报错。
users表迁移代码
Schema::create('users', function (Blueprint $table) { $table->id('users_id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamp('email_verified_at')->nullable(); $table->rememberToken(); $table->timestamps(); });
drawings表迁移代码
Schema::create('drawings', function (Blueprint $table) { $table->id('drawings_id'); $table->string('name'); $table->integer('canvas_size'); $table->foreign('users_id') ->references('users_id')->on('users')->onDelete('cascade'); $table->timestamps(); });
报错信息
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'users_id' doesn't exist in table (SQL: alter table `drawings` add constraint `drawings_users_id_foreign` foreign key (`users_id`) references `users` (`users_id`) on delete cascade)
解决方案
核心问题是drawings表中未先定义users_id字段,且字段类型需与users表的主键类型严格匹配:
users表通过$table->id('users_id')创建的主键为**无符号大整数(unsignedBigInteger)**类型- 错误写法:使用
$table->unsignedInteger('users_id')->nullable();(类型不匹配) - 正确操作:先在
drawings表中添加对应类型的字段,再设置外键关联
修正后的drawings表迁移代码:
Schema::create('drawings', function (Blueprint $table) { $table->id('drawings_id'); $table->string('name'); $table->integer('canvas_size'); // 先定义与users表主键类型匹配的外键字段 $table->unsignedBigInteger('users_id')->nullable(); // 再设置外键关联 $table->foreign('users_id') ->references('users_id')->on('users')->onDelete('cascade'); $table->timestamps(); });
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

