【问题标题】:Why is creating Foreign Key in Laravel 5.8 failing?为什么在 Laravel 5.8 中创建外键失败?
【发布时间】:2019-07-26 05:07:11
【问题描述】:

下面的迁移脚本在旧版本的 Laravel 中运行顺利,但我将它添加到我的新 Laravel 5.8 并运行脚本。我收到Error: foreign key was not formed correctly

评估迁移:

public function up() { 
    Schema::create('evaluation', function (Blueprint $table) { 
        $table->increments('id'); 
        $table->integer('user_id')->unsigned()->index(); 
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

用户迁移:

public function up() { 
    Schema::create('users', function (Blueprint $table) { 
        $table->bigIncrements('id'); 
        $table->timestamps();
    });
}

【问题讨论】:

  • users 表在您运行之前是否存在?您不能在表存在之前声明外键引用它。
  • 我不是 laravel 专家,但看起来 users.id 将成为 BIGINT 但您将 evaluation.user_id 声明为 INT UNSIGNED?那是行不通的。它们必须是完全相同的数据类型。
  • 啊哈,我找到了blog,它确认 Laravel 增量类型默认是无符号的。但是您应该将外键列声明为 bigInteger 以匹配它引用的主键的大小。
  • 我也不确定在 Laravel 语法中 bigIncrements 是否隐式声明 user.id 作为该表的主键?外键应引用作为主键或唯一键的列。
  • @BillKarwin 我将迁移代码中的user_id 更改为$table->unsignedBigInteger('user_id'); 现在可以正常工作了。

标签: mysql laravel eloquent


【解决方案1】:

正如我们在上面的 cmets 中所讨论的,外键列必须与其引用的主键具有相同的数据类型。

您将 user.id 主键声明为 $table->bigIncrements('id'),在 MySQL 语法中将变为 BIGINT UNSIGNED AUTO_INCREMENT

您必须将外键声明为 $table->unsignedBigInteger('user_id'),这将在 MySQL 中变为 BIGINT UNSIGNED,使其与 user.id 列的外键兼容。

【讨论】:

  • 啊哈! unsignedBigInteger,不仅仅是bigInteger
  • 使用 laravel 5.5。这种方法仍然失败。我什至分开了声明外键的模式。还是没有运气
  • @S.Domeng,我建议您查看清单here。如果仍然失败,请尝试提出一个新问题并展示您的尝试。如果您只说“它失败了。”,您将不会得到任何有用的答案。您必须展示您尝试过的内容并显示两个表的 SHOW CREATE TABLE 输出,并显示确切的错误消息你明白了。
  • 谢谢@BillKarwin,但我在评论区。我不确定在这里解释是否是正确的提问方式。继续前进,我发现了问题...来自我的外键约束通过将迁移引用表文件的名称设为复数来修复。说 create_users_table。我的错误是我有一个单数 create_user_table 名称。
  • 已编辑:不确定这是否是我最后抛出外键约束的那个。尽管如此,这是文档中的约定。但是,我也确实重新启动了我的服务器。我用拉拉贡。您可以使用 XAMPP、WAMP 甚至在 Vagrant 中进行操作。
【解决方案2】:
  update your `integer('user_id')` to `bigInteger('user_id')`
public function up() { 
        Schema::create('evaluation', function (Blueprint $table) { 
            $table->increments('id'); 
            $table->bigInteger('user_id')->unsigned()->index(); 
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2017-03-11
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多