gpt4 book ai didi

laravel - 使用 Laravel 获取当前行的排名

转载 作者:行者123 更新时间:2023-12-02 08:41:15 25 4
gpt4 key购买 nike

在我的 Laravel 4 应用程序中,我的 users 表有一个 votes 列。我想找到当前用户的排名。我已经可以使用 User::orderBy('votes', 'desc')->take(10) 获得前 10 名用户,但我想在该列表下方显示当前用户的排名.理想情况下,这将是这样的:

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

我得到登录的用户,假设我按投票对用户表排序,我要求他的排名。

有人知道我是否可以用 Eloquent 做到这一点吗?

最佳答案

虽然仍然有些 hacky,但您可以通过 Eloquent 中的自定义 getter(修改器)来完成。

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

然后您可以将用户排名作为一个属性。

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

关于laravel - 使用 Laravel 获取当前行的排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16343482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com