samedi 5 décembre 2020

Position of a user based on his sum of amount in list of sum of amount of all users

I have a database with fields

id
user_id
amount

i want to find the position(rank) of the user based on his total amount

what i have done is to run as 2 queries like below

        $user_id = '12';

        $user_donations = \Donation::select(\DB::raw('sum(amount) as donation_total'))
        ->whereHas('user')
        ->groupBy('user_id')
        ->orderBy('donation_total', 'DESC')
        ->where('user_id', $user_id)
        ->first();

        $ranking = \Donation::select('user_id', \DB::raw('sum(amount) as donation_total'))
        ->whereHas('user')
        ->groupBy('user_id')
        ->orderBy('donation_total', 'DESC')
        ->having('donation_total', '>=', $user_donations->donation_total)
        ->get();
     
       $user_rank = $ranking->count();

is it possible to combine to single query?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire