Tasos
Tasos

Reputation: 7577

Order by the difference of two columns in Laravel 5.3

I have an eloquent query where one of the orderBy is the difference of two columns.

$mymodel = Level::where([['ColA', 5], ['ColB', 10], ['ColC', 7]])
                 ->orderBy('ColA', 'Desc')
                 ->orderBy('ColA' - 'ColB', 'Desc')
                 ->orderBy('ColC', 'Desc')
                 ->orderBy('ColD', 'Asc')
                 ->pluck('userId')->toArray();

The exact same code on localhost with sqlite works without an error. But on production with MySQL has the following error

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'order clause' (SQL: select `userId` from `levels` where (`ColA` = 5 and `ColB` = 10 and `ColC` = 7) order by `ColA` desc, `0` desc, `ColC` desc, `ColD` asc)

Upvotes: 1

Views: 2710

Answers (1)

Sturm
Sturm

Reputation: 4285

$model = Level::where($wheres)
              ->orderByRaw('(ColA - ColB) DESC')
              ->pluck('userId')
              ->toArray();

Upvotes: 10

Related Questions