nechitagabriel
4 years ago
1281
17
General

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

Posted 4 years ago by nechitagabriel

I've been following along Jeff's tutorial "Laravel 5 Fundamentals".

I'm at video 14, "Eloquent Relationships", and trying to do a migration but keep getting this error:


  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `articles` add constraint articles_user_id_foreign foreign key (`user_id`) references `users` (`id`) on delete cascade)

This is my users migration file

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

this is my articles migration

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('user_id')->unsigned();;
            $table->string('title');
            $table->text('body');
            $table->timestamps();
            $table->timestamp('published_at');
            
            
            
        });

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

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

}

I'm a beginner, so sorry if my question is too basic, but I tried a few solutions before coming here for help. :D

Anyone has any pointers for me?

Best,

Gabriel

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