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.
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.
Use yii\db\Expression
:
$orderBy = (new \yii\db\Query())
->select('*')
->from('product')
->orderBy([new \yii\db\Expression('FIELD (id, 3,1,2,4)')])
->all();
You can push all order condtitions into array and then put this array into orderBy method like above. ta = enum type field.
$orderBy[] = new \yii\db\Expression("ta = 'MALE' desc, ta = 'ALL' desc");
$orderBy[] = new \yii\db\Expression("id asc, name desc");
$query->orderBy($orderBy);
The sorting is possible also by the column's inner value, not only id. This can be helpful in case of an update. You update a value that must be at the bottom of your table, so:
->orderBy([new Expression('FIELD (column_name, value)ASC')])->all();
If you looking how to sort with Fields with Yii2, try this
$array_ids = [5,7,3,9,2,8,1] //simple array
$modelsObj = Model::find()
->where(['id' => $array_ids]) // find only needed id's
->limit(5) //add limit if you need
->orderBy([new \yii\db\Expression('FIELD(id, '. implode(',', $array_ids) . ')')]) // sorting them as in array
->all();
Product::find()->orderBy([new \yii\db\Expression('FIELD (id,3,1,2,4)'), 'id' => SORT_ASC])->all()
This example code to sort country data ASC with the First column India
$data = Countries::find()
->orderBy([new \yii\db\Expression('FIELD (country_code, "IN") DESC, country_name ASC')])
->asArray()
->all();
output:
Array
(
[0] => Array
(
[id] => 101
[country_name] => India
[country_code] => IN
)
[1] => Array
(
[id] => 18
[country_name] => Bahrain
[country_code] => BH
)
[2] => Array
(
[id] => 65
[country_name] => Egypt
[country_code] => EG
)
[3] => Array
(
[id] => 194
[country_name] => Saudi Arabia
[country_code] => SA
)
)