[英]Laravel migration throw database query exception error
我正在嘗試編寫具有外部關系的laravel數據庫遷移。 在數據庫遷移期間拋出查詢異常錯誤。
我厭倦了使用laravel規則遷移表,但是在遷移過程中卻顯示了意外錯誤。
用戶表
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name', 150);
$table->string('email', 150)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone', 150);
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
角色表
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('role_name',255);
$table->longText('role_description',255);
$table->integer('sort_order');
$table->enum('status',['A','I','D'])->comment('A-active','I-inactive,D-delete');
$table->enum('is_deleted',['Y','N'])->comment('Y-yes,N-no');
$table->timestamps();
$table->bigInteger('created_by');
$table->bigInteger('updated_by')->default(0);
$table->bigInteger('deleted_by')->default(0);
$table->timestamp('deleted_at')->nullable();
});
Illuminate \\ Database \\ QueryException:SQLSTATE [HY000]:常規錯誤:1215無法添加外鍵約束(SQL:更改表
jt_users
添加約束users_role_id_foreign
外鍵(role_id
)在刪除級聯上引用jt_roles
(id
)
您不能將外鍵添加到不存在的表中。 就您而言,您正在嘗試在創建roles
表之前創建一個role_id
。
在roles
表遷移中,一旦創建了roles
表,您將需要更新users
表:
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('role_name',255);
$table->longText('role_description',255);
$table->integer('sort_order');
$table->enum('status',['A','I','D'])->comment('A-active','I-inactive,D-delete');
$table->enum('is_deleted',['Y','N'])->comment('Y-yes,N-no');
$table->timestamps();
$table->bigInteger('created_by');
$table->bigInteger('updated_by')->default(0);
$table->bigInteger('deleted_by')->default(0);
$table->timestamp('deleted_at')->nullable();
});
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
注意:對表進行更改時, 請使用Schema::table()
而不是Schema::create()
。
在roles
遷移的down()
方法上,您需要刪除外鍵和字段:
Schema::table('users', function (Blueprint $table) {
$table->dropForeign(['role_id']);
$table->dropColumn('role_id');
});
首先,必須遷移具有“主鍵”(用戶)的表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.