jeudi 16 novembre 2017

Many to Many on Laravel migration

I have 3 tables to connect each other. Tables name's roles, role_user, and users. I want to make migration on laravel and adding some constraint. and here's what in my role tables migration:

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

and here's my Users table migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->string('name');
    $table->string('email')->unique();
    $table->integer('role_id')->unsigned();
    $table->string('password');
    $table->boolean('active')->default(0);
    $table->softDeletes();
    $table->rememberToken();
    $table->timestamps();

    $table->foreign('role_id')->references('id')
        ->on('roles')
        ->onDelete('restrict')
        ->onUpdate('cascade');
});

and here's my role_user table migration:

    Schema::create('role_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('role_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->timestamps();

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

in my Migration order i put roles table on top of users already but i got this kind of errors:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_role_id_foreign` foreign key (`role_id`) refer
  ences `roles` (`id`) on delete restrict on update cascade)

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

can anyone help me why i can get this kind of errors? Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zHfanW
via IFTTT

Aucun commentaire:

Enregistrer un commentaire