Home > Mobile >  PHP How to orderby two columns when the data is equal
PHP How to orderby two columns when the data is equal

Time:11-18

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": "[email protected]",
                "empresa": "c"
            },
            {
                "totalTime": "00:05:00",
                "TotalPoints": "120",
                "id": 2,
                "name": "Randomname",
                "email": "[email protected]",
                "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": "[email protected]",
                "empresa": "gmail"
            },
            {
                "totalTime": "00:08:00",
                "TotalPoints": "120",
                "id": 1,
                "name": "Randomname",
                "email": "[email protected]",
                "empresa": "c"
            }
}

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

CodePudding user response:

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();
  • Related