I'm not allowed to modify the structure of the database although the foreign key did not set up properly; so that I have to modify the relations.
To be more specific, the post_id instead of stays on the child table, means the answers table, it stays on the parent table, which is the posts table. The foreign key column has to concate string like that 8578|58757|7855.
This worked perfectly for me even 5 years later on Laravel 12.
Context:
I have a Legislator model with a relationship to a state model but when the state_id is 52, it actually returns "United States" instead of the state since they are a federal legislator. This is how the data comes from the datasource.
In those cases, I still wanted to return the state relationship but needed to overwrite the default where query in the relationship and add a new one using the state abbreviation.
Here's my code:
/**
* Get the state where the legislator resides.
*
* @return Eloquent\Relations\BelongsTo
*/
public function state(): Eloquent\Relations\BelongsTo
{
if ($this->state_id === 52 && $this->district) {
// For federal legislators, we need to match
// the last two characters of district to get the state abbreviation
// Store the belongsTo relation
$relation = $this->belongsTo(State::class);
// Reset the default state_id query
$relation->getBaseQuery()->wheres = [];
$relation->getBaseQuery()->bindings['where'] = [];
// Pull off the last two characters to get the state abbreviation
$stateAbbr = Str::of($this->district)->substr(3, 2)->lower();
// Add the actual where query to find the state.
return $relation->where('abbreviation', $stateAbbr);
}
// The normal relationship for every other case.
return $this->belongsTo(State::class);
}