【Laravel5.8】SQLSTATE[HY000]: General error: 1005 Can't create tableを解決したい
migrationファイルに参照制約をつけると未だに100%ぶつかる以下のエラー。
1 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table 'book_store.#sql-18ac_2c' (errno: 150)")
こういう奴ですが、原因はほぼ確実に参照しようとしているidのデータ型と〇〇_idなどで引っ張ってきているデータ型が違うということ。
今回の場合は以下のような違いがありました。
booksマイグレーション
class CreateBooksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned(); ★ $table->timestamps(); $table ->foreign('category_id') ->references('id') ->on('categories') ->onDelete('cascade'); }
categoriesマイグレーション
public function up() { Schema::create('categories', function (Blueprint $table) { $table->bigIncrements('id');★ $table->timestamps(); }); }
星の付いているbooksの「integer('category_id')->unsigned();」と「bigIncrements('id');★」の型を合わせることで解決します。
以下が解決したコード。
booksマイグレーション
Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned(); $table->timestamps(); $table ->foreign('category_id') ->references('id') ->on('categories') ->onDelete('cascade');
categoriesマイグレーション
Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->timestamps();