在 Yii2 中按字段排序 [英] Order By Field IN Yii2

查看:37
本文介绍了在 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

这篇关于在 Yii2 中按字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆