Reputation: 23
I want to get ranking number in Laravel.
DB is here.
id Bigint
name string
point BigInt
.....
I want to get ranking number in point column. What should I do?
now code is this.
User::where('id', 1)->first();
if I have these datas.
id name score ...
1 AA 10
2 CD 10
3 ER 40
4 DR 5
I want to get ranking number ex) id 1 => 2 (or3) ex) id 3 => 1
Upvotes: 1
Views: 528
Reputation: 5662
You can get the rank as below:
User::selectRaw("SELECT id, name, point, FIND_IN_SET( point, (
SELECT GROUP_CONCAT( DISTINCT point ORDER BY point DESC ) FROM
user )
) AS rank
FROM user")
->get()
Upvotes: 1
Reputation: 176
Try this. Here is the raw query :
SELECT id,name,point,
@curRank := @curRank + 1 AS rank
FROM user u, (SELECT @curRank := 0) r
ORDER BY point;
You can write it in laravel as follows :
DB::select("SELECT id,name,point,
@curRank := @curRank + 1 AS rank
FROM user u, (SELECT @curRank := 0) r
ORDER BY point;");
Upvotes: 0