嗨,我正在尝试添加两个引用同一张表的外键列。但是我被这个错误困扰。我花了很多时间试图找出代码中的问题。我已经在stackoverflow中浏览了所有可能的重复帖子,但是找不到解决方案。
我的代码很长,因此我在这里提到重要的部分,如果您需要有关此问题的更多信息,请告诉我。
这是我的外键关系
$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(),
答案 0 :(得分:1)
迁移是根据创建日期来加载的,也许是因为您在数据库中创建关系之前先定义了一些关系,所以可能会出现问题。
换句话说,必须先创建城市,国家,公民身份和工作地点迁移。
您可以附上项目迁移的屏幕截图吗?只是为了获得更多细节。