[英]getting 'SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint' error with migration
[英]SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Error
我想在用戶表上添加角色列。 但我得到了這個錯誤。
我的用戶遷移
Schema::create('users', function (Blueprint $table) {
$table->increments("id");
$table->string('name');
$table->string("company_name")->unique();
$table->string('email')->unique();
$table->string("phone")->unique();
$table->boolean("status");
$table->integer("role")->unsigned();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role')->references('id')->on('roles')->cascadeOnUpdate()->cascadeOnDelete();
});
還有我的角色遷移
Schema::create('roles', function (Blueprint $table) {
$table->increments("id");
$table->string('name');
});
問題很可能是由錯誤的遷移順序引起的。 當您將roles
表id
存儲在users
表中時,您必須先遷移roles
表,然后再遷移users
表。 由於我不知道您的表的順序,我將根據您的帖子順序假設users
表首先遷移,然后是roles
表,這就是users
表無法獲取roles
表的 id 引用的原因. 嘗試將roles
表的日期重命名為users
表之前的日期,然后運行php artisan cache:clear
然后php artisan migrate:fresh
。
只是一些建議,因為您已指定您使用的是 Laravel 8,請使用id();
function 而不是使用increments("id");
. 要遵循 Laravel 的外鍵規則,請使用role_id
作為外鍵而不是role
。
而不是使用: $table->foreign('role')->references('id')->on('roles')->cascadeOnUpdate()->cascadeOnDelete();
利用:
$table->foreignId('role_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
嘗試改變
$table->integer("role")->unsigned();
至
$table->foreignId('role_id');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
確保角色遷移在用戶遷移之前在遷移中具有預先順序,您可以編輯角色遷移的遷移名稱(編輯時間戳使其在用戶之前遷移)
您需要按如下方式更改代碼,
Schema::create('users', function (Blueprint $table) {
$table->increments("id");
$table->string('name');
$table->string("company_name")->unique();
$table->string('email')->unique();
$table->string("phone")->unique();
$table->boolean("status");
$table->unsignedBigInteger("role");
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role')->references('id')->on('roles')->cascadeOnUpdate()->cascadeOnDelete();
});
根據此處的文檔,您使用integer
而不是unsignedBigInteger
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.