jasonb
4 years ago
479
23
General

Cannot add foreign key constraint

Posted 4 years ago by jasonb

I am trying to go through the tagging video in L5 and when I try to migrate I get this error: [Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter table article_tags add constraint article_tags_article_id_foreign foreign key (article_id) references articles (id) on delete cascade)

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

public function up()
    {
        Schema::create('tags', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('article_tags', function(Blueprint $table)
        {
            $table->integer('article_id')->unasigned()->index();


            $table->integer('tag_id')->unasigned()->index();

            $table->timestamps();
        });

        Schema::table('article_tags', function(Blueprint $table)
        {
            $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
        });

    }



    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tags');
        Schema::drop('article_tag');
    }

}

I tried to separate the the migration into two parts thinking that would solve this issue.
What did I do wrong?

Please sign in or create an account to participate in this conversation.