Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ranking field how to use set variables in MySQL?

I have a users table with an integer field called ep.

Now, I want to retrieve all users from a specific group ordered by the EP field, and with a generated MySQL field called rank.

This is what I tried:

DB::transaction(function()
{
    DB::statement("SET @rank:=0");
    $group = Sentry::findGroupByName('Player');
    $users = Sentry::getUserProvider()->createModel()
        ->join('throttle', 'throttle.user_id', '=', 'users.id')
        ->join('users_groups', 'users_groups.user_id', '=', 'users.id')
        ->where('throttle.banned', 0)
        ->where('throttle.suspended', 0)
        ->where('users_groups.group_id', $group->id)
        ->orderBy('ep', 'desc')
        ->paginate(100, array('@rank := @rank + 1', 'users.ep', 'users.username'));
});

But I got this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '@rank := @rank + 1' in 'field list' (SQL: select `@rank := @rank + 1`, `users`.`ep`, `users`.`username` from `users` inner join `throttle` on `throttle`.`user_id` = `users`.`id` inner join `users_groups` on `users_groups`.`user_id` = `users`.`id` where `throttle`.`banned` = 0 and `throttle`.`suspended` = 0 and `users_groups`.`group_id` = 2 order by `ep` desc limit 100 offset 0) 
like image 653
goldlife Avatar asked Aug 31 '25 17:08

goldlife


1 Answers

Ran into this same issue and found the correct solution on : https://laravel.io/forum/12-18-2014-how-to-initialize-user-defined-mysql-variables

DB::statement( DB::raw( 'SET @total := 0'));
$results = DB::select( $query); // only the "select.." part here
like image 135
maximus 69 Avatar answered Sep 02 '25 05:09

maximus 69