Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 OrderBy specific field value first

Tags:

mysql

yii2

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.

like image 552
Giest Avatar asked Dec 01 '22 13:12

Giest


1 Answers

Use yii\db\Expression :

$orderBy = (new \yii\db\Query())
         ->select('*')
         ->from('product')
         ->orderBy([new \yii\db\Expression('FIELD (id, 3,1,2,4)')])
         ->all();
like image 164
Insane Skull Avatar answered Dec 05 '22 10:12

Insane Skull