我尝试迁移我的表,但它显示错误:
errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table
users
add constraintusers_role_id_foreign
foreign key (role_id
) referencesroles
(id
))
这是我的表格:
Schema::create('users', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('fullname');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles');
$table->rememberToken();
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name')->unique();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('posts', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('content');
$table->string('image');
$table->timestamps();
});
最佳答案
问题是,当您使用 roles
表的外键创建 users
表时,roles
表不存在但是,因此您无法添加引用它的外键。
我还注意到,roles
表还有一个引用 users
表的外键,这使得情况变得更加棘手。
如果您绝对确定 roles
表需要 users
表的外键,那么您需要从 users 中删除外键创建
表定义,并在创建 roles
表后将其作为 alter table
单独添加回来。
但是,我不确定 roles
表是否应该有一个到 users
表的 fk(除非它代表创建该角色的用户),因为您可以一个角色有多个用户。如果您正在建模多对多关系,那么这不是正确的方法。但这与当前错误无关,因此仅将其视为旁注。
关于php - (Laravel) 错误号 : 150 "Foreign key constraint is incorrectly formed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101878/