Reputation: 530
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;
Upvotes: 1
Views: 1515
Reputation: 125
Wrap your custom sorting using \yii\db\Expression e.g
->orderBy(new \yii\db\Expression('FIELD(SORTING,1,2,3,0)'))
Upvotes: 2
Reputation: 133360
Using letteral sql code should work
MyTable::find()->orderBy(" FIELD(SORTING,1,2,3,0) ")->all();
Upvotes: 1