[英]Get most common values in column of related model in Eloquent
I am using Eloquent ORM and I am trying to find out what the most successful sport for a club is, based on wins in tournaments.我正在使用 Eloquent ORM,并试图根据锦标赛中的胜利找出俱乐部最成功的运动是什么。
I have the tables clubs
, tournaments
, sports
and tournament_results
, each represented by a model ( Club
, Tournament
, Sports
, TournamentResult
) with relationships.我有clubs
、 tournaments
、 sports
和tournament_results
,每个表都由一个具有关系的模型( Club
、 Tournament
、 Sports
、 TournamentResult
)表示。 The relevant columns in my tables:我的表中的相关列:
clubs
, tournaments
, sports
each contain id
, name
clubs
、 tournaments
、 sports
每个都包含id
, name
tournament_results
: id
, tournament
, club
, place
. tournament_results
: id
、 tournament
、 club
、 place
。
Relations:关系:
Club
has HasMany
with ClubResults
Club
有HasMany
和ClubResults
TournamentResult
has BelongsTo
with Tournament
and BelongsTo
with Club
TournamentResult
有BelongsTo
with Tournament
和BelongsTo
with Club
Tournament
has HasMany
with TournamentResults
and BelongsTo
with Sport
Tournament
有HasMany
with TournamentResults
和BelongsTo
with Sport
Sport
has HasMany
with Tournament
Sport
有HasMany
Tournament
The idea I had about getting my desired result is something like this:我对获得想要的结果的想法是这样的:
Club -> TournamentResults -> where place = 1 -> Tournaments -> get n (eg 3) most common sports in this set
What I have so far is:到目前为止我所拥有的是:
$club = Club::findOrFail($id);
$club->tournamentResults()->where('place', 1)->with('tournament.sport');
But now I don't know how to continue.但现在我不知道如何继续。 Can someone help me in finding a solution?有人可以帮我找到解决方案吗?
Add this relationship to your Club
model:将此关系添加到您的Club
模型中:
public function wonTournaments() {
return $this->belongsToMany(Tournament::class, 'tournament_results')
->wherePivot('place', 1);
}
Then you can do this:然后你可以这样做:
$topSport = $club->wonTournaments->groupBy('sport_id')
->sortByDesc(function($tournaments) {
return $tournaments->count();
})
->first()->first()->sport;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.