Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order By Field IN Yii2

Tags:

yii2

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

How to solve with ::find() ?

UPD: should be like

$recipes = Recipes::find()
    ->where(['id' => $recipeIds])
    ->orderBy(['id' => array_reverse($recipeIds)])
    ->limit($this->count)
    ->all();
like image 471
Hyper Avatar asked Nov 28 '22 14:11

Hyper


1 Answers

Try that:

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

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

like image 152
vitalik_74 Avatar answered Dec 24 '22 09:12

vitalik_74