我正在使用laravel开发一个登录应用程序,我想为用户扮演角色,但是遇到了这个错误
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table `accounting`.`role_user`
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `role_user` add constraint `role_user_role_id_foreign` foreign key (`role_id`) references `roles` (`id`))
这是导致提到的错误的代码:
CreateUsersTable
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
CreateRolesTable
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
CreateRoleUser
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->cascade('delete');
$table->foreign('user_id')->references('id')->on('users')->cascade('delete');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
有什么想法可以解决此问题吗?
答案 0 :(得分:0)
确保两种情况下的数据类型均匹配。您的主键数据类型和外键数据类型必须相同。
其次,请确保按顺序放置迁移文件。假设您有三个表角色,用户和role_user。您想要在具有role_user的角色和具有role_user的用户之间建立关系。在迁移目录中,角色和用户表(迁移文件)应该首先出现,然后作为role_user表的role_user表(迁移文件)包含对这两个表的引用。该顺序将在创建文件时保留。因此,您可以重命名文件,更改时间格式(格式为year_month_date_seconds),使其位于role_user表之前。或者,您可以为其创建目录。然后分别迁移它们。
答案 1 :(得分:-1)
没有太大帮助,但仍然不应该如此
$table->foreign('role_id')->references('id')->on('roles')->cascade('delete');
$table->foreign('user_id')->references('id')->on('users')->cascade('delete');
替换为
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');