asinan

Laravel 5.6 Eloquent Relationship

Posted 6 months ago by asinan

I'm making a website with teams, team matches and match events. Each team match has a home team and an away team. Each match event has a team match and a team.

The problem is I get team match events for the particular team match but for home team i get away team events as well.

teams

id|name

team_matches

id|home_team_id|away_team_id

team_match_events

id|team_match_id|team_id|event

Team Model

public function homeTeamMatch()
{
    return $this->hasMany(TeamMatch::class, 'home_team_id');
}

public function awayTeamMatch()
{
    return $this->hasMany(TeamMatch::class, 'away_team_id');
}
public function teamMatchEvent()
{
    return $this->hasMany(TeamMatchEvent::class, 'team_id');
}

TeamMatch Model

public function homeTeam()
{
    return $this->belongsTo(Team::class, 'home_team_id');
}

public function awayTeam()
{
    return $this->belongsTo(Team::class, 'away_team_id');
}
public function teamMatchEvent()
{
    return $this->hasMany(TeamMatchEvent::class, 'team_id');
}

TeamMatchEvent Model

public function teamMatch()
{
    return $this->belongsTo(TeamMatch::class);
}

public function team()
{
    return $this->belongsTo(Team::class);
}

In HomeController

$last_match_results = TeamMatch::with('homeTeam.teamMatchEvent')->first();

The Problem is i do get Match Events for the homeTeam, but not for the particular match. Events of the all the matches for the team is fetched. Any Ideas?

Please sign in or create an account to participate in this conversation.