Kenneth Chan
Kenneth Chan

Reputation: 530

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;

Upvotes: 1

Views: 1515

Answers (2)

Paul Ngumii
Paul Ngumii

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

ScaisEdge
ScaisEdge

Reputation: 133360

Using letteral sql code should work

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

Upvotes: 1

Related Questions