简体   繁体   中英

Unable to create a foreign key in Laravel migrations

I am trying to create a foreign key relation in user table with user_role table.

user table migration

user_role column is a foreign key column

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('user_role')->nullable();
            $table->foreign('user_role')->references('role')->on("user_role")->onDelete('cascade');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->text('profile_photo_path')->nullable();
            $table->timestamps();
        });
    }

user_role table

public function up()
    {
        Schema::create("user_role",function(Blueprint $table){
            $table->increments('id');
            $table->string("role")->nullable();
        });
    }

migrations are not applying following error is generating

Illuminate\Database\QueryException 

  SQLSTATE[HY000]: General error: 1005 Can't create table `ecommerce`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `users` add constraint `users_user_role_foreign` foreign key (`user_role`) references `user_role` (`role`) on delete cascade)

  at F:\ecommerce-indian\ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:678
    674▕         // If an exception occurs when attempting to run a query, we'll format the error
    675▕         // message to include the bindings with SQL, which will make this exception a
    676▕         // lot more helpful to the developer instead of just the database's errors.
    677▕         catch (Exception $e) {
  ➜ 678▕             throw new QueryException(
    679▕                 $query, $this->prepareBindings($bindings), $e
    680▕             );
    681▕         }
    682▕

  1   F:\ecommerce-indian\ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471
      PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `ecommerce`.`users` (errno: 150 "Foreign key constraint is incorrectly formed")")      

  2   F:\ecommerce-indian\ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471
      PDOStatement::execute() 

what's the problem with foreign key where I'm doing wrong.

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->unsignedBigInteger('user_role')->nullable();
            $table->foreign('user_role')->references('id')->on("user_role")->onDelete('cascade');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->text('profile_photo_path')->nullable();
            $table->timestamps();
        });
    }

before create users migration create user_role migration and use field id on user_role

your role must be unique.

$table->string("role")->unique();

this is the code for users migration

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->text('profile_photo_path')->nullable();
            $table->timestamps();
        });
    }

then create "user_role" migration with this code.

public function up()
    {
        Schema::create("user_role",function(Blueprint $table){
            $table->increments('id');
            $table->string("role")->unique();
        });
    }

and then create another migration like

php artisan make:migration add_user_role_in_users_table

in that add this code

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('user_role')->nullable();
            $table->foreign('user_role')->references('role')->on("user_role")->onDelete('cascade');
        });
    }

and then run

php artisan migrate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM