【问题标题】:Cannot add foreign key constraint in Laravel Migration无法在 Laravel 迁移中添加外键约束
【发布时间】:2020-03-12 19:01:29
【问题描述】:

我发现发布了许多类似的问题,但似乎没有一个解决方案适用于我的情况。当我运行“php artisan migrate:fresh”时,它会抛出错误......

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1215 无法添加外键约束(SQL:alter table slicer_profiles 添加约束 slicer_profiles_user_id_foreign 删除级联时外键 (user_id) 引用 users (id)

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

    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(),但没有改变。任何解决此问题的帮助将不胜感激!

【问题讨论】:

    标签: php mysql laravel foreign-keys database-migration


    【解决方案1】:

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

    Schema::create('slicer_profiles', function (Blueprint $table) {
        ...
        $table->bigInteger('user_id')->unsigned()->index();
        // or $table->unsignedBigInteger('user_id')->index();
        ...
    });
    

    【讨论】:

    • 谢谢您,它立即修复了它。我想我正在关注的教程有点过时了,也许 Laravel 将 'users' auth 表上的 'id' 从 INT 更改为 BIGINT 或其他东西,因为它是编写的。感谢您的帮助!
    • 是的,将users 表调整为使用bigIncrements 是一个较新的变化
    猜你喜欢
    • 2019-03-24
    • 2017-03-27
    • 2021-08-30
    • 2020-09-21
    • 2020-01-20
    • 2019-07-31
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多