php - 无法在 Laravel 中创建外键

标签 php mysql laravel foreign-keys

我正在尝试在我的 user_details 表中创建一个外键。 我的 user_details 表中有 2 个外键,一个是 user_id 引用 Sentinel 创建的主用户表中的用户 ID。我还有一个国家表,我想在其中将 country_of_origin 字段设置为国家表中的国家数字代码。但是每次我执行迁移时,我都会收到以下错误

"Foreign key constraint is incorrectly formed"

我的国家表的架构

 public function up()
{
    Schema::create('countries', function (Blueprint $table) {
        $table->collation = 'utf8_general_ci';
        $table->charset = 'utf8';
        $table->integer('id');
        $table->string('name');
        $table->string('alpha_2');
        $table->string('alpha_3');
        $table->timestamps();
        $table->engine = 'InnoDB';
    });
}

id 字段是 ISO 3166-1 数字国家代码,而不是该行的自动递增 ID。此外,此表的数据是使用播种器从 JSON 文件提供的。

我的用户详细信息表的架构

public function up()
{
    Schema::create('user_details', function (Blueprint $table) {
        $table->increments('id',true);
        $table->integer('user_id')->unsigned();
        $table->string('date_of_birth');
        $table->integer('country_of_origin')->unsigned();
        $table->integer('contact_number');
        $table->timestamps();
        $table->engine = 'InnoDB';
    });
    Schema::table('user_details', function($table) {
        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('country_of_origin')->references('id')->on('countries');
    });
}

创建国家表的迁移在执行 user_details 迁移之前首先执行。

如果我删除 $table->foreign('country_of_origin')->references('id')->on('countries'); 我不会收到任何错误。我也试过 $table->integer('country_of_origin'); 但我仍然遇到同样的错误。

解决方案 问题是因为 countries 表中 id 字段的名称,但实际上,它不是自动递增的列,而是具有基于种子数据的固定值。

我改变了我的模式如下 国家模式

 public function up()
{
    Schema::create('countries', function (Blueprint $table) {
        $table->collation = 'utf8_general_ci';
        $table->charset = 'utf8';
        $table->increments('id',true);
        $table->integer('num_id')->unique();
        $table->string('name');
        $table->string('alpha_2');
        $table->string('alpha_3');
        $table->timestamps();
        $table->engine = 'InnoDB';
    });
}

为自动递增的 id 添加了一个额外的字段,并将 SO 3166-1 数字国家代码存储在 num_id 字段中

在User details表中,只是改变了以下内容

 $table->foreign('country_of_origin')->references('num_id')->on('countries');

最佳答案

countries 表中的id 必须是主键

关于php - 无法在 Laravel 中创建外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052148/

相关文章:

php - Smarty/如何包含PHP函数来压缩CSS文件

php - 忽略 PHP 函数的返回值有问题

php - 我的表单请求有什么问题导致简单的验证规则不起作用?

javascript - Laravel 405 方法不允许通过 GET 调用 POST 方法

php - MySql 查询返回多个结果,更新时所有内容都会更新,但我只需要更新其中一个

php - 读取带有空格和 () 的文件名

MySQL:根据子查询的相关子查询获取行数

python - 安装 Django 的 mysql 模块

php - 使用 PHP 上下移动记录

php - 在Laravel 5.7中更改(电子邮件)按钮的颜色