Getting the current row's rank with Laravel

落爺英雄遲暮 提交于 2019-12-22 17:40:08

问题


In my Laravel 4 app, my users table has a votes column. I'd like to find the current user's rank. I can already get the top 10 users with User::orderBy('votes', 'desc')->take(10), but I'd like to display the current user's rank below that list. Ideally, this would go something like:

Auth::user()->rank('orderBy', 'votes', 'desc');

I get the logged in user, I ask for his rank assuming I order the users table by votes.

Does anybody know if there's some way I can do this with Eloquent?


回答1:


Although still somewhat hacky you can do it via a custom getter (mutator) in Eloquent.

public function getRankAttribute()
{
    return $this->newQuery()->where('votes', '>=', $this->votes)->count();
}

You can then get the users rank as an attribute.

$rank = Auth::user()->rank;



回答2:


Something like:

$currUser = DB::table('users')->where('votes','>=',Auth::user()->votes)->count();

And display $currUser by the user details below the top 10 list?

Hopefully this helps.



来源:https://stackoverflow.com/questions/16343482/getting-the-current-rows-rank-with-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!