简体   繁体   English

在 Eloquent 中相关模型的列中获取最常见的值

[英]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.我有clubstournamentssportstournament_results ,每个表都由一个具有关系的模型( ClubTournamentSportsTournamentResult )表示。 The relevant columns in my tables:我的表中的相关列:
clubs , tournaments , sports each contain id , name clubstournamentssports每个都包含id , name
tournament_results : id , tournament , club , place . tournament_resultsidtournamentclubplace

Relations:关系:
Club has HasMany with ClubResults ClubHasManyClubResults
TournamentResult has BelongsTo with Tournament and BelongsTo with Club TournamentResultBelongsTo with TournamentBelongsTo with Club
Tournament has HasMany with TournamentResults and BelongsTo with Sport TournamentHasMany with TournamentResultsBelongsTo with Sport
Sport has HasMany with Tournament SportHasMany 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM