Search code examples
mysqlyii2

Yii2 OrderBy specific field value first


This is my table:

Product
id | name
1 | A
2 | B
3 | C
4 | D

And I want ID 3 in first position:

Product
id | name
3 | C
1 | A
2 | B
4 | D

I can only with the "OrderBy" assign ASC and DESC values. It gives error if you assign a numeric value.


Solution

  • Use yii\db\Expression :

    $orderBy = (new \yii\db\Query())
             ->select('*')
             ->from('product')
             ->orderBy([new \yii\db\Expression('FIELD (id, 3,1,2,4)')])
             ->all();