我正在尝试在我的 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/