在 Yii2 中按字段排序

问题描述:

我遇到了这个问题,但在 yii 仪器中没有找到任何解决方案.有人知道如何解决这个问题吗?

I got this problem and not found any solution with yii instrument. Someone know how to solve this problem ?

最终,我使用了这个糟糕的代码

Eventually, i used this bad code

$params = [];
foreach ($recipeIds as $i => $recipeId) {
    $params[':id_'.$i] = $recipeId;
}

$recipes = Recipes::findBySql(
        'SELECT
            *
        FROM
            {{%recipes}}
        WHERE
            `id` IN ('.implode(', ',array_keys($params)).')
        ORDER BY
            FIELD (id, '.implode(',', array_reverse(array_keys($params))).')
        LIMIT
            :limit',
        $params + [':limit' => $this->count]
    )
    ->all();

如何用 ::find() 解决?

How to solve with ::find() ?

UPD:应该像

$recipes = Recipes::find()
    ->where(['id' => $recipeIds])
    ->orderBy(['id' => array_reverse($recipeIds)])
    ->limit($this->count)
    ->all();

试试看:

$recipes = Recipes::find()
    ->where(['in', 'id', $recipeIds])
    ->orderBy([new \yii\db\Expression('FIELD (id, ' . implode(',', array_reverse(array_keys($params))) . ')')])
    ->limit($this->count)
    ->all();

orderByFIELD (...) 一起使用,请参阅 https://github.com/yiisoft/yii2/issues/553

For use orderBy with FIELD (...) see https://github.com/yiisoft/yii2/issues/553