SQLSTATE[23000]:违反完整性约束:19 FOREIGN KEY 约束失败 => Laravel
SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed => Laravel
您好,我正在尝试添加两个引用相同 table 的外键列。但我坚持这个错误。我花了很多时间试图找出我的代码的问题。我已经在 Whosebug 中浏览了所有可能重复的帖子,但我找不到解决方案。
我的代码很长,所以我在这里提到了重要的部分,如果您需要有关该问题的更多信息,请告诉我。
这是我的外键关系
$table->unsignedBigInteger('country_id');
$table->unsignedBigInteger('city_id');
$table->unsignedBigInteger('work_location');
$table->unsignedBigInteger('citizenship');
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('city_id')->references('id')->on('cities');
$table->foreign('work_location')->references('id')->on('cities');
$table->foreign('citizenship')->references('id')->on('countries');
这些是我的主要模特关系
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
public function country()
{
return $this->belongsTo(Country::class,'country_id');
}
public function citizenship()
{
return $this->belongsTo(Country::class,'citizenship');
}
public function work_location()
{
return $this->belongsTo(City::class, 'work_location');
}
这就是我通过 phpunit 向模型发送数据的方式
'citizenship'=>Country::factory()->create();,
'work_location'=>City::factory()->create();,
'city_id' => City::factory()->create();,
'country_id' => Country::factory()->create(),
迁移是根据创建日期加载的,可能是因为您在数据库中创建关系之前定义了一些关系。
换句话说,城市、国家、公民身份和 work_location 迁移必须在引用之前创建。
能否附上项目迁移的屏幕截图?只是想了解更多详情。
您好,我正在尝试添加两个引用相同 table 的外键列。但我坚持这个错误。我花了很多时间试图找出我的代码的问题。我已经在 Whosebug 中浏览了所有可能重复的帖子,但我找不到解决方案。
我的代码很长,所以我在这里提到了重要的部分,如果您需要有关该问题的更多信息,请告诉我。
这是我的外键关系
$table->unsignedBigInteger('country_id');
$table->unsignedBigInteger('city_id');
$table->unsignedBigInteger('work_location');
$table->unsignedBigInteger('citizenship');
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('city_id')->references('id')->on('cities');
$table->foreign('work_location')->references('id')->on('cities');
$table->foreign('citizenship')->references('id')->on('countries');
这些是我的主要模特关系
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
public function country()
{
return $this->belongsTo(Country::class,'country_id');
}
public function citizenship()
{
return $this->belongsTo(Country::class,'citizenship');
}
public function work_location()
{
return $this->belongsTo(City::class, 'work_location');
}
这就是我通过 phpunit 向模型发送数据的方式
'citizenship'=>Country::factory()->create();,
'work_location'=>City::factory()->create();,
'city_id' => City::factory()->create();,
'country_id' => Country::factory()->create(),
迁移是根据创建日期加载的,可能是因为您在数据库中创建关系之前定义了一些关系。
换句话说,城市、国家、公民身份和 work_location 迁移必须在引用之前创建。
能否附上项目迁移的屏幕截图?只是想了解更多详情。