B
B
BonBon Slick2017-01-23 11:25:37
Laravel
BonBon Slick, 2017-01-23 11:25:37

General error: 1215 Cannot add foreign key constraint Laravel 5.3?

I don't understand why, the first foreign_key works, but the second one doesn't.

// это pivot table, беру id юзера,  делаю связь, все работает, но не надет поставить связь с roles таблицей
         Schema::create('user_role', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->integer('user_id')->unsigned()->nullable();
            $table->integer('role_id')->unsigned()->nullable();
            $table->timestamps();
            $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');
            // $table->foreign('id')->references('role_id')->on('roles')->onDelete('cascade');
        });

Such an error:
[Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter
  table `user_role` add constraint `user_role_id_foreign` foreign key (`id`) referenc
  es `roles` (`role_id`) on delete cascade)



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

Used by InnoDB.

What did I overlook?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2019-03-04
@BonBonSlick

Since Laravel 5.8, the autoincrement method (id) has changed. was And now: Therefore, bind to bigInteger

$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

H
hakkol, 2017-01-23
@hakkol

Maybe so:

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question