首页 > 解决方案 > 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');

标签: phpmysqllaravel

解决方案


如果要返回当前已验证的位置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;

推荐阅读