Reputation: 133
Hi I'm trying to add two foreign key columns refering to the same table. But I'm stuck with this error. I've spent a lot of time trying to figure out the issue with my code. I've gone through all possible duplicate posts as this in stackoverflow but I couldn't find the solution.
I have a really long code, so I am mentioning the important chunks here, let me know if you need any further info on the issue.
this is my foreign key relationship
$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');
these are my lead Model relationships
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');
}
And this is how I send data to the model through phpunit
'citizenship'=>Country::factory()->create();,
'work_location'=>City::factory()->create();,
'city_id' => City::factory()->create();,
'country_id' => Country::factory()->create(),
Upvotes: 2
Views: 1746
Reputation: 86
Migrations are loaded based on the date they were created, maybe the problem occurs because you are defining some relationship before creating it in the database.
In other words, city, country, citizenship and work_location migrations must be created before they are referenced.
Can you attach a screenshot of the project's migrations? Just to have more details.
Upvotes: 4