简体   繁体   中英

Get results from model, order by sum of columns

In Laravel 5.3 I have a User model. I want to have the 10 users with the highest ranking on my server. The ranking is based on a sum of the columns Rank_a , Rank_b and Rank_c . How can I do that?

This is the code I have so far:

$users = User::take(10)
        ->select(DB::raw('sum(Rank_a+Rank_b+Rank_c) AS total_points'))
        ->orderBy('total_points')
        ->get();
return response()->json($users);

You should specify the columns you want to get in select() . Also, since you want to get the users with the highest rankings, you should sort them in descending order.

Assuming that you need to get the columns id and username :

$users = User::select(
    DB::raw('id, username, Rank_a + Rank_b + Rank_c AS total_points')
)->orderBy('total_points', 'desc')->take(10)->get();

If you want to get all columns:

$users = User::select(
    DB::raw('users.*, Rank_a + Rank_b + Rank_c AS total_points')
)->orderBy('total_points', 'desc')->take(10)->get();

And if you just want to get an array of one column, say, id :

$users = User::select(
    DB::raw('id, Rank_a + Rank_b + Rank_c AS total_points')
)->orderBy('total_points', 'desc')->take(10)->pluck('id');

You can try the following query:

$users = User::take(10)
            ->select('users.*', DB::raw('(Rank_a+Rank_b+Rank_c) AS total_points'))
            ->orderBy('total_points', 'desc')
            ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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