php artisan migrate を使用して、「books」テーブルと「categories」テーブルの外部キーを設定しようとしていますが、次のエラーが発生しました。
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table `books` add constraint `books_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))
書籍移行ファイル:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string("image");
$table->string("title");
$table->string("description")->nullable();
$table->string("author");
$table->string("cover");
$table->integer("nod")->nullable();// Number of downloads
$table->integer("rating")->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
カテゴリ移行ファイル:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string("title");
$table->string("image");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
モバイル アプリ API で使用するために、これに関する支援が本当に必要です。誰かが助けてくれることを願っています。
ベストアンサー1
問題は移行自体にあります。これをよく見てください
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table `books` add constraint `books_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))
テーブルを開こうとしていますcategories
が、基本的にはテーブルが存在しないか、まだ作成されていません。HeidiSQL、Navicat、PMA などの GUI を使用すると、テーブルを表示できます。
Laravel の移行では、ファイルの先頭のタイムスタンプを取得して、どの移行を最初に移行するかを決定します。
books テーブルの前に、必ずカテゴリ テーブルを作成してください (これは参照を持つすべてのテーブルにも適用されます)。または、次のようにファイル名を変更する (タイムスタンプを変更する) だけです。
2020_01_01_1234_create_books_table.php
2020_01_01_5678_create_categories_table.php
これに
2020_01_01_1234_create_categories_table.php
2020_01_01_5678_create_books_table.php
次に実行してphp artisan migrate:fresh
移行を更新します。