无法在Laravel Migration中添加外键约束

我发现发布了许多类似的问题,但是这些解决方案似乎都不适合我的情况。当我运行“ php artisan migration:fresh”时,它会抛出错误...

  

Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规错误:   1215无法添加外键约束(SQL:更改表   slicer_profiles添加约束slicer_profiles_user_id_foreign   外键(user_id)引用删除级联上的usersid

  • 所有创建的表都是InnoDB
  • 'users'表是在我的表之前创建的
  • 我将代码分为两步,然后分配外键

    Schema::create('slicer_profiles',function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->index();
        $table->string('title');
        $table->text('description');
        $table->string('slicer');
        $table->string('machine');
        $table->softDeletes();
        $table->timestamps();
    });
    
    Schema::table('slicer_profiles',function($table) {
        $table->foreign('user_id')->unsigned()
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
    

我检查了auth users表,它似乎使用了UNSIGNED BIGINT,因此我也尝试在引用上设置-> unsigned(),但没有任何更改。解决该问题的任何帮助将不胜感激!

NICHNICHNICH 回答:无法在Laravel Migration中添加外键约束

如果users.id字段是BIGINT,则需要将users_id上的slicer_profiles列设为BIGINT,以便两个字段具有完全匹配的类型。

Schema::create('slicer_profiles',function (Blueprint $table) {
    ...
    $table->bigInteger('user_id')->unsigned()->index();
    // or $table->unsignedBigInteger('user_id')->index();
    ...
});
本文链接:https://www.f2er.com/3087856.html

大家都在问