Laravel migration: “Foreign key constraint is incorrectly formed” (errno 150)

后端 未结 22 884
有刺的猬
有刺的猬 2020-11-30 07:21

When migrating my DB, this error appears. Below is my code followed by the error that I am getting when trying to run the migration.

Code



        
22条回答
  •  一生所求
    2020-11-30 07:53

    Laravel 5.8

    In the foreign key column use unsignedBigInteger to avoid mismatch foreign key data type problem . For example let us assume we have two tables questions and replies
    Questions table will look:

     public function up()
        {
            Schema::create('questions', function (Blueprint $table) {
                $table->bigIncrements('id');
                 $table->text('body');
                 $table->integer('user_id')->unsigned();
                $table->timestamps();
            });
        }
    

    Replies table look like :

    public function up()
    {
        Schema::create('replies', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('body');
            $table->unsignedBigInteger('question_id');
            $table->integer('user_id')->unsigned();
            $table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
            $table->timestamps();
        });
    }
    

提交回复
热议问题