maranovot
maranovot

Reputation: 445

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');
        });

Upvotes: 3

Views: 1319

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can't add foreign key to a column with different type, so just change it, for example in users table:

$table->unsignedInteger('sid')->unique();

Upvotes: 4

Related Questions