php - Laravel how to get current user rank by points?
问题描述
I need to get current user rank by points. Example. I'm getting all total users count by:
$userCount = User::count();
I have users table with points column. USERS table:
USER ID | USERNAME | POINTS
1 USERA 32.25
2 USERB 2.25
3 USERC -12.25
I need to take selected user rank by his points.
Updated: My blade to show user profile:
public function show($slug)
{
/** @var User $user */
$user = User::whereSlug($slug)->firstOrFail();
if (! $user->isActivated()) {
$this->alertInfo(trans('app.access_denied'));
return;
}
$user->access_counter++;
$user->save();
$this->title("Player $user->username profile");
$this->pageView('users::show', compact('user'));
}
Route file:
ModuleRoute::context('Users');
ModuleRoute::resource('users', 'UsersController', ['only' => ['index', 'show', 'edit', 'update']]);
ModuleRoute::get('players/{slug}', 'UsersController@show')->name('users.show');
解决方案
如果要返回当前已验证的位置User
,可以执行以下操作:
// get all users and order them by the `points` field in descending order
$usersByPoints = User::orderBy('points', 'desc')->get();
// search through your users to find the record where
// the name of the user record matches that of the autneticated user
$position = $usersByPoints->search(function ($user, $key) {
return $user->name == auth()->user()->name;
});
// add 1 to the poisition as it will be zero indexed
return $position + 1;
更新
根据您的评论,让我们定义一条路线web.php
:
Route::get('/user', UserProfileController::class);
UserProfileController
使用工匠在您的目录中创建app/Http/Controllers
(或者如果您愿意,可以手动创建):
php artisan make:controller UserProfileController
在这个控制器内部,定义一个调用的函数,当有人访问路由并添加上面的代码__invoke()
时,Laravel 将调用该函数:/user
public function __invoke()
{
$usersByPoints = User::orderBy('points', 'desc')->get();
$position = $usersByPoints->search(function ($user, $key) {
return $user->name == auth()->user()->name;
});
return view('user.profile', ['position' => $position + 1]);
}
在上面return view()
指定当有人访问/user
路由并将position
属性传递给视图时要呈现的刀片视图。
在 处创建刀片视图resources/views/user/profile.blade.php
。然后,您可以$position
按如下方式访问该属性:
Your position is {{ $position }}!
更新 2 - 在数据库上进行
MySQL 没有row number
像其他数据库引擎那样的函数概念,但是,对于那些关心的人,可以使用 PHP 在数据库而不是内存中执行上述查询:
$position = (int) (DB::select(
'select (@row_number:=@row_number + 1) as `position` from users, (select @row_number:=0) as t where id = ? order by points desc',
[auth()->user()->id]
)[0])->position;
return $position + 1;
推荐阅读
- angular - Angular 12 升级后样式问题
- reactjs - React 状态下的过滤器错误
- php - 付费会员专业版:这是使自定义列排序的任何方法吗?
- laravel - Laravel 文件未存储在存储目录中
- reactjs - 我在反应中对 ag-grid 做错了什么?
- elasticsearch - 查询 DSL 正则表达式模式不适用于某些字符串
- db2 - 将 Db2 选择查询结果导出到 CSV 时没有出现标题
- swift - 将类对象存储在 UserDefaults 中时,枚举编码值为 nil。可编码协议已被继承
- javascript - 如何获取 mxGraph 地图的坐标?
- pandas - 重新采样 10D 但直到月底