在 yii2 中按 rand() 排序

Order by rand() in yii2

我想在 yii2 中编写以下查询,但无法获得预期的输出:

SELECT * FROM user where category_id=5 ORDER BY rand() LIMIT 4

为此我做了以下工作:

$data= User::find()->where(['category_id'=> 5])->orderBy(['rand()'])->limit(4);

但是它生成如下命令

SELECT * FROM `user` WHERE `category_id`=5 ORDER BY `0` LIMIT 4

哪个不是有效的 mysql 语句,那么我应该怎么做才能使查询正确?

我的目标是从 user table.

中随机获取 4 条记录

我不是 yii2 查询生成器的真正专家,但是,指定顺序应该会有所帮助

$data= User::find()->where(['category_id'=> 5])->orderBy(['rand()' => SORT_DESC])->limit(4);

将其包装成yii\db\Expression以防止转义并删除数组部分:

use yii\db\Expression;

...

$query = User::find()
    ->where(['category_id' => 5])
    ->orderBy(new Expression('rand()'))
    ->limit(4);