问题
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