1
php artisan migrate

Результат:

[Illuminate\Database\QueryException]

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table articles add constraint articles_category_id_foreign foreign key (category_id) references categories (id) on delete cascade)

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Миграция:

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->string('url')->unique();
            $table->text('description')->nullable();
            $table->text('keywords')->nullable();
            $table->integer('category_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('articles', function (Blueprint $table) {
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->dropForeign(['category_id']);
        });

        Schema::drop('articles');
    }

Engine: InnoDB (по умолчанию)

Актуальное решение проблемы найти не смог.

1 ответ 1

1

Странно, но проблема решилась следующим образом.

Schema::table('articles', function (Blueprint $table) {
   $table->foreign('category_id')
      ->references('id')
      ->on('categories')
      ->onDelete('cascade');
});

Я поместил в миграцию категорий, так как из ошибки было понятно что он не может найти таблицу categories что бы на основе её primary связать foreign.

Однако, все делают так как изложено в вопросе, странно почему у меня это не сработало.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.