我有三个表需要相互连接。这些表的名称是roles、role_user和users。我想在laravel上进行迁移并添加一些限制。以下是我的角色表迁移内容:
这是我的用户表迁移:
这是我的 role_user 表迁移文件:
在我的迁移顺序中,我已经将角色表放在用户表之上,但我仍然遇到了这种错误:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
这是我的用户表迁移:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('active')->default(0);
$table->softDeletes();
$table->rememberToken();
$table->timestamps();
});
这是我的 role_user 表迁移文件:
Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->unique(['role_id', 'user_id']);
$table->foreign('role_id')->references('id')->on('roles')
->onDelete('cascade')->onUpdate('cascade');
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')->onUpdate('cascade');
});
在我的迁移顺序中,我已经将角色表放在用户表之上,但我仍然遇到了这种错误:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `role_user` add constraint `role_user_role_id_foreign` foreign key (`role_id
`) references `roles` (`id`) on delete cascade on update cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
role_user
表是否在最后创建。此外,在回滚时,请检查约束是否也被删除。更多参考资料请参见此处。 - Pathros