无法将外键添加到数据库表

时间:2019-03-31 16:57:22

标签: laravel-5

我试图在我的问题表中添加外键约束,但是当我运行php artisan migration时,出现以下错误:

SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:更改表questions添加约束questions_best_answer_id_foreign外键(best_answer_id)引用answersid)删除SET NULL)

“ 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']);
        });
    }
}

我的答案模型

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

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

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

我正在尝试迁移到数据库以在答案表上创建FK,但出现上述错误。我还转换了所有数据库,以使用InnoDB引擎。

我的代码中有错误吗?

谢谢!

0 个答案:

没有答案
相关问题