el-skunk's avatar

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.

0 likes
3 replies
krisi_gjika's avatar

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.

el-skunk's avatar

@krisi_gjika Not quite the selected team has the opponent and this could be the home or the away team id.

When you say create an attribute could you elaborate I've spent hours today and can't seem to find a good solution.

krisi_gjika's avatar

@el-skunk something like:

public function homeTeam(): HasOne
{...}

public function awayTeam(): HasOne
{...}

public function getOpponentTeam(int $team_id): TeamModel
{
    return $this->home_team->id === $team_id ? $this->away_team : $this->home_team;
}

Please or to participate in this conversation.