Tuesday, April 11, 2017

Laravel 1215 Cannot add foreign key constraint

Hello I have trouble with my database migrations in my laravel application

This is the error:

[Illuminate\Database\QueryException]                                         
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL  
  : alter table `transactions` add constraint `transactions_user_sid_foreign`  
   foreign key (`user_sid`) references `users` (`sid`))

This is my transactions migration:

public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_sid')->index();
            $table->unsignedInteger('store_id')->index();
            $table->unsignedInteger('value');
            $table->timestamps();
            $table->softDeletes();
        });
    }

This is the users migration:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->unsignedInteger('role_id')->index();
            $table->string('sid')->unique();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

And finally my foreign keys:

Schema::table('transactions', function (Blueprint $table){
            $table->foreign('user_sid')->references('sid')->on('users');
            $table->foreign('store_id')->references('id')->on('stores');
        });



via M. Novotny

Advertisement