The issue with the query is that the total_score and games_played columns are not available in the query result. To fix this, you can use subqueries to calculate these values and then use them in the main query. Here's an updated version of the query:
$topMembers = DB::table('members')
->join(DB::raw('(SELECT player1_id as id, SUM(player1_score) as total_score, COUNT(*) as games_played FROM games GROUP BY player1_id
UNION ALL
SELECT player2_id as id, SUM(player2_score) as total_score, COUNT(*) as games_played FROM games GROUP BY player2_id) as games'), function ($join) {
$join->on('members.id', '=', 'games.id');
})
->select('members.id', 'members.name', 'games.total_score', 'games.games_played')
->groupBy('members.id')
->havingRaw('COUNT(*) >= 10')
->orderByRaw('games.total_score / games.games_played DESC')
->limit(10)
->get();
In this version, we're using subqueries to calculate the total_score and games_played values for each member. We're then joining this subquery with the members table and using the calculated values in the main query. We're also using the orderByRaw method to sort the results by the calculated value.