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

时间:2018-03-04 01:09:16

标签: php laravel orm eloquent

我正在使用Eloquent ORM,我试图找出俱乐部最成功的运动,基于比赛中的胜利。
我有表clubstournamentssportstournament_results,每个表都由模型(ClubTournament,{{1}表示},Sports)与关系。我表格中的相关栏目:
TournamentResultclubstournaments每个都包含sportsid
nametournament_resultsidtournamentclub

关系:
place ClubHasManyClubResults TournamentResult BelongsTo Tournament BelongsTo Club Tournament HasMany TournamentResults BelongsTo Sport Sport HasMany Tournament Club -> TournamentResults -> where place = 1 -> Tournaments -> get n (e.g. 3) most common sports in this set$club = Club::findOrFail($id); $club->tournamentResults()->where('place', 1)->with('tournament.sport');

我对获得理想结果的想法是这样的:
CMake Error at cmake/modules/FindEigen3.cmake:42 (file): file failed to open for reading (No such file or directory): /usr//usr/include/eigen3/Eigen/src/Core/util/Macros.h

到目前为止我所拥有的是:

/usr/

但现在我不知道如何继续。有人可以帮我找到解决方案吗?

1 个答案:

答案 0 :(得分:1)

将此关系添加到您的Club型号:

public function wonTournaments() {
    return $this->belongsToMany(Tournament::class, 'tournament_results')
        ->wherePivot('place', 1);
}

然后你可以这样做:

$topSport = $club->wonTournaments->groupBy('sport_id')
    ->sortByDesc(function($tournaments) {
        return $tournaments->count();
    })
    ->first()->first()->sport;