dimanche 31 mars 2019

Unable to add foreign key to DB table

I am trying to add a foreign key constraint into my questions table but when I run php artisan migrate I get the following error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table questions add constraint questions_best_answer_id_foreign foreign key (best_answer_id) references answers (id) on delete SET NULL)

Up and down methods in my "add_foreign_best_answer_id_to_questions_table.php"

public function up()
    {
        Schema::table('questions', function (Blueprint $table) {
            //Define the foreign key
            $table->foreign('best_answer_id')
                  ->references('id')
                  ->on('answers')
                  ->onDelete('SET NULL');
        });
    }

    public function down()
    {
        Schema::table('questions', function (Blueprint $table) {
            $table->dropForeign(['best_answer_id']);
        });
    }
}

My Answer Model

 public static function boot()
    {
        parent::boot();

        static::created(function ($answer){
            $answer->question->increment('answers_count');
        });

        static::deleted(function($answer){
            $answer->question->decrement('answers_count');
        });
    }


I am trying to migrate to the DB to create a FK on the answers table but I get the error above.

Are there errors in my code?

Thank you!



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

Aucun commentaire:

Enregistrer un commentaire