[英]Laravel 7.0 MySQL SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table
[英]SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'landlords'
我對 laravel 很陌生,遇到了這個錯誤消息
( SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'landlords' (SQL: alter table `apartments` add constraint `apartments_landlord_id_foreign` foreign key (`landlord_id`) references `landlords` (`id`))
) .
我已經更改了公寓和房東表之間的遷移日期,但錯誤仍然存在,如圖所示。 公寓遷移文件的正下方是地主表,地主表比公寓表有更早的日期。
這是公寓的桌子代碼
{
Schema::create('apartments', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->longText('description');
$table->decimal('price');
$table->foreignId('user_id')->constrained('users');
$table->foreignId('landlord_id')->constrained('landlords');
$table->timestamps();
});
}
``` ....dated 2021_02_16_232034_create_apartments_table
Here's the landlord's table migration file.
``` public function up()
{
Schema::create('landlords', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('apartment_id')->constrained('apartments');
$table->foreignId('user_id')->constrained('users');
$table->timestamps();
});
}
```dated 2021_02_16_232129_create_landlords_table
在您的第一次遷移(create_apartments_table)中,您在仍然不存在的地主表上創建了一個約束,因此出現了錯誤。
為避免這種情況,您可以在創建地主表后延遲創建約束。 因此,在第一次遷移中刪除約束,在第二次遷移(create_landlords_table)中,在您創建了地主表之后,您修改了公寓表以具有與地主表的約束。
public function up()
{
Schema::create('landlords', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('apartment_id')->constrained('apartments');
$table->foreignId('user_id')->constrained('users');
$table->timestamps();
});
Schema::table('apartments', function(Blueprint $table) {
$table->foreignId('landlord_id')->constrained('landlords');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.