Skip to content
Advertisement

PHP How to orderby two columns when the data is equal

This return come from this query.

$getRanking = DB::table('users')
->select(DB::raw('totalTime ,sum(userPoints)+sum(extraPoints) as TotalPoints, id, name, email'))
->groupby('id','name', 'email','totalTime')
->orderby('TotalPoints','desc','totalTime','desc')
->limit(10)
->get();

Let`s understand my doubt, i have this data.

    {
        "sucesso": true,
        "data": [
            {
                "totalTime": "00:08:00",
                "TotalPoints": "120",
                "id": 1,
                "name": "Randomname",
                "email": "ddddd@c.com",
                "empresa": "c"
            },
            {
                "totalTime": "00:05:00",
                "TotalPoints": "120",
                "id": 2,
                "name": "Randomname",
                "email": "aaaa@gmail.com",
                "empresa": "gmail"
            }
}

When i have the equal points data 0 is 120 and data 1 is 120. I need to display the first data with less totalTime in this case needs to be like this :

    {
        "sucesso": true,
        "data": [
            {
                "totalTime": "00:05:00",
                "TotalPoints": "120",
                "id": 2,
                "name": "Randomname",
                "email": "aaaa@gmail.com",
                "empresa": "gmail"
            },
            {
                "totalTime": "00:08:00",
                "TotalPoints": "120",
                "id": 1,
                "name": "Randomname",
                "email": "ddddd@c.com",
                "empresa": "c"
            }
}

Can i manage this only with SQL or i need to order with PHP ?

Advertisement

Answer

Use orderBy() as multiple times as you need:

$getRanking = DB::table('users')
->select(DB::raw('totalTime ,sum(userPoints)+sum(extraPoints) as TotalPoints, id, name, email'))
->groupBy('id','name', 'email','totalTime')
->orderBy('TotalPoints','DESC')
->orderBy('totalTime','DESC')
->limit(10)
->get();

or use orderByRaw() for multiple ordering:

$getRanking = DB::table('users')
    ->select(DB::raw('totalTime ,sum(userPoints)+sum(extraPoints) as TotalPoints, id, name, email'))
    ->groupBy('id','name', 'email','totalTime')
    ->orderByRaw('TotalPoints DESC, totalTime DESC')
    ->limit(10)
    ->get();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement