获得当前行的排名与Laravel [英] Getting the current row's rank with Laravel
问题描述
在我的Laravel 4应用中,我的用户
表中有一个投票
列。我想查找当前用户的排名。我可以使用 User :: orderBy('votes','desc') - > take(10)
获得前10名用户,但我想显示当前用户的排名低于该列表。理想情况下,这将会像:
Auth :: user() - > rank('orderBy','votes' ,'desc');
我得到登录的用户,我要求他的排名,假设我通过投票命令用户表。
有没有人知道有没有办法用Eloquent来做到这一点?
虽然仍然有点黑客,你可以通过一个定制的getter(mutator)在Eloquent中实现。
public function getRankAttribute()
{
return $ this-> newQuery() - > where('votes','> =',$ this-> votes) - > ;计数();
}
然后,您可以将用户排名作为属性。
$ rank = Auth :: user() - > rank;
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?
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;
这篇关于获得当前行的排名与Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!