Kenneth Chan Kenneth Chan - 15 days ago 5
PHP Question

Yii Framework; How to use OrderBy() with custom sorting

I use Yii 2.x
I would like to use OrderBy() with custom sorting. But It go wrong.

How do I run something like this

MyTable::find()->orderBy('WHEN SORTING = '1' THEN '1' WHEN SORTING = '2' THEN '2' WHEN SORTING = '3' THEN '3' ELSE SORTING ASC')->all();


I also tried below but failed.

MyTable::find()->orderBy('FIELD(SORTING,1,2,3,0)')->all;

Answer

Using letteral sql code should work

MyTable::find()->orderBy(" FIELD(SORTING,1,2,3,0) ")->all();