【发布时间】:2019-01-24 00:32:53
【问题描述】:
我有三张桌子:
PLAYERS with a team_id
TEAMS
SCORES with a player_id
事情是这样的:
我的球队有得分的球员,我想对球队进行排名。因此,如果一支球队有几名球员,则基本上是按球员获得最好的成绩,然后将其相加。
例如:
团队 A 有球员 1 和球员 2。 玩家 1 有 3 个分数(例如 300、150 和 500),我想只保留最好的一个(所以 500)。
你知道我该怎么做吗? 由于球队与分数之间或球员与分数之间没有直接关系,我不明白如何在这三者之间建立联系。
感谢您的帮助!
编辑
评分模型
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');
}
}
玩家模型
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');
}
}
团队模式
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');
}
}
【问题讨论】:
-
所以你想得到一个团队中所有球员的最好成绩,将它们相加并将其存储在特定团队下。对吗?
-
没错! :)
标签: laravel relationship