4

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.

Giest
  • 495
  • 1
  • 10
  • 21
  • 5
    I am not sure that I understand your question. You want to select the rows in this table and order them like in the second example? What would be the "ordering" criteria in this case? Why the row [3, C] should be the first one? – Marco Altieri Jan 09 '16 at 02:10
  • http://stackoverflow.com/questions/14104055/ordering-by-specific-field-value-first but Yii2 – Giest Jan 09 '16 at 02:12

7 Answers7

14

Use yii\db\Expression :

$orderBy = (new \yii\db\Query())
         ->select('*')
         ->from('product')
         ->orderBy([new \yii\db\Expression('FIELD (id, 3,1,2,4)')])
         ->all();
gvlasov
  • 18,638
  • 21
  • 74
  • 110
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
3
->OrderBy("FIELD(id,3,4,2,1)");
AsgarAli
  • 2,201
  • 1
  • 20
  • 32
1

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);
Stas Panyukov
  • 348
  • 3
  • 8
1

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();
Matteo Koi
  • 11
  • 1
0

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();
Zlocorp
  • 314
  • 3
  • 4
0
Product::find()->orderBy([new \yii\db\Expression('FIELD (id,3,1,2,4)'), 'id' => SORT_ASC])->all()
Janki Rathod
  • 107
  • 6
0

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
        )

)
Ricky Riccs
  • 41
  • 1
  • 5