why are players table had both id and player_id?
Oct 20, 2022
5
Level 1
Get collection of parent class with the child that has maximum value of a column
I have 3 tables:
competitions [id, name, status]
clubs [id, name]
players [id, name, score, competition_id, club_id]
with appropriate relations on their respective model class. So I need a query that shows how many players who are competition winners at each club. For a player to be considered a competition winner, they must have the max score (and not draw with anyone).
So far I have tried, the following:
// App/Models/Player
public function winner(): bool
{
return $this->score > $this->competition->players()->where('players.id', '<>', $this->id)->max('votes');
}
And in my controller:
public function index()
{
$players = Player::all()->filter(function ($value, $key){
return $value->winner();
})->pluck('club_id');
$clubWinners = $players->countBy();
return Party::whereIn($players->unique())->get()->map(function ($item) use ($clubWinners){
$item['no_of_wins'] = $clubWinners->get($item->id);
return $item;
})
}
which does do the trick. However, it's a terrible method, and very inefficient. I know there's a better solution out there, but I just can't think of any. Please any help will be appreciated.
Please or to participate in this conversation.