mysql Yii2 OrderBy特定字段值优先

nafvub8i  于 2023-02-21  发布在  Mysql
关注(0)|答案(7)|浏览(176)

这是我的table

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

我想要ID3在第一个位置:

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

我只能用“OrderBy”分配ASC和DESC值。如果你分配一个数字值,它会给错误。

ia2d9nvy

ia2d9nvy1#

使用yii\db\Expression

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

frebpwbc2#

->OrderBy("FIELD(id,3,4,2,1)");
5t7ly7z5

5t7ly7z53#

您可以将所有订单条件推入数组,然后将该数组放入orderBy方法中,如上所述。ta =枚举类型字段。

$orderBy[] =  new \yii\db\Expression("ta = 'MALE' desc, ta = 'ALL' desc");
$orderBy[] =  new \yii\db\Expression("id asc, name desc");
$query->orderBy($orderBy);
wydwbb8l

wydwbb8l4#

如果你想知道如何用Yii2对字段进行排序,试试这个

$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();
cnwbcb6i

cnwbcb6i5#

Product::find()->orderBy([new \yii\db\Expression('FIELD (id,3,1,2,4)'), 'id' => SORT_ASC])->all()
0lvr5msh

0lvr5msh6#

也可以按列的内部值排序,而不仅仅是按id排序。这在更新时会很有帮助。您更新的值必须位于表的底部,因此:

->orderBy([new Expression('FIELD (column_name, value)ASC')])->all();
zu0ti5jz

zu0ti5jz7#

此示例代码用于对国家/地区数据进行ASC排序,其中第一列为India

$data = Countries::find()
        ->orderBy([new \yii\db\Expression('FIELD (country_code, "IN") DESC, country_name ASC')])
        ->asArray()
        ->all();

输出:

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
        )

)

相关问题