Ad

Octobercms - Order Records By Variable, If Value Is The Same, Order By Second Variable

- 1 answer

I'm creating a frontend leaderboard on october cms. The system i am currently using is the following:

When i edit one of the inputs that stores the values on the db, javascript gets the value and sums it with all other values in a hidden input that stores the sum in a db field.

So when i want to get the list of records by total points i just do:

use RainLab\User\Models\User;

function onInit() {
   $this['activatedUsers'] = User::whereIsActivated(true)->orderBy('RankPoints', 'desc')->get();
}

Ordering the result by that field that contains the sum.

That is what is currently in place and working just fine. What i am trying to achieve is to sort records by one variable (x for example). But if two users have the same value for x, it sorts them with another variable (y). Eventually i would like to do this with more than two variables, but i want to start with this simple two variable system so that i can understand the thought process.

Example:

enter image description here

The user (a) is on top of user (b) with the current method, because it has a higher number in other variable. But if i want to sort all users by Level, and then by Gym Points, Player (b) would actually be on top.

Hope you guys can understand & help out, Thanks in advance.

EDIT:

Adding a uys can understand & help out, Thanks in advance.

EDIT:

Adding a second orderby with the second variable on the query seems to work, is this method correct?

Ad

Answer

With MySQL, it is possible to order results by multiple values simply by using several ORDER BY conditions.

For example, the following will order the users firstly by level, and secondly by rank points.

$users = User::whereIsActivated(true)
    ->orderBy('Level', 'desc')        // x
    ->orderBy('RankPoints', 'desc')   // y
    ->get();
Ad
source: stackoverflow.com
Ad