aren't they both opponents of each other? The eloquent way to do this is to have two relation and create an attribute to determine which one is the selected one, you would have to eager load both.
Jul 28, 2023
3
Level 1
Dynamic eloquent relation
I have a scenario where a DB table stores sport results and there is a home_team_id and an away_team_id
What I want to do in an eloquent relation is determine which of these team IDs is the opponent based on an ID held in a config file. The code below is what I've tried as a function in a model. But I can't access any $this attributes at this level in the model.
I've proved this works because I can hard code the ID in teh variable to test and it will pull back the correct ID. I just can't make this dynamic.
if ($this->home_team_id == config('team.selected_team_id'))
{
$team_id = 'away_team_id';
}
elseif ($this->away_team_id == config('team.selected_team_id'))
{
$team_id = 'home_team_id';
}
return $this->hasOne(Team::class, 'id', $team_id);
Is there a more Eloquent way to do this? I'm reluctant to add another DB column to duplicate an ID which I could then jsut query. This doesn't feel right.
Please or to participate in this conversation.