I have three tables :
PLAYERS with a team_id
TEAMS
SCORES with a player_id
The thing is :
My teams have players who have scores and I would like to make a ranking of teams. So basically get the best score by players and make the sum of it if a team has several players.
For example :
TEAM A has player 1 and player 2. Player 1 has 3 scores (300, 150 and 500 for example) and I'd like to keep only the best one (so 500).
Do you have any idea how I can do that ? As there's no direct relation between teams and scores or between players and scores, I don't understand how I can make the link between these 3.
Thanks for your help !
EDIT
Score Model
class Score extends Model
{
protected $fillable = [
'value', 'player_id'
];
public function player()
{
return $this->belongsTo('App\Player');
}
public function players_scores()
{
return $this->hasManyThrough('App\Team', 'App\Player');
}
}
Player model
class Player extends Model
{
protected $fillable = [
'name','email','team_id'
];
/**
* Get the team of the player
*/
public function team()
{
return $this->belongsTo('App\Team');
}
/**
* Get the scores of the player
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function scores()
{
return $this->hasMany('App\Score');
}
/**
* Get the maximum score from the player
*
* @return mixed
*/
public function getBestScoreAttribute()
{
return $this->scores->max('value');
}
}
Team model
class Team extends Model
{
protected $fillable = ['name','logo'];
protected $appends = ['score'];
public function players()
{
return $this->hasMany('App\Player');
}
/*
* Collect all the team players scores
*/
public function players_scores()
{
return $this->hasManyThrough('App\Score', 'App\Player');
}
public function scores()
{
return $this->hasMany('App\Score');
}
/*
* Sum the score of all team players to get the team score
*/
public function getScoreAttribute()
{
return $this->players_scores->sum('value');
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community