12

I want to write following query in yii2, but I can't get the expected output:

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

For that I have done following:

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

But it generates the command like following

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

Which is not a valid mysql statement,so what should I do to get the query right?

My aim is to get any random 4 records from user table.

peterh
  • 11,875
  • 18
  • 85
  • 108
Mike Ross
  • 2,942
  • 5
  • 49
  • 101
  • 1
    Unless you don't care about performance, never order by `rand()`. It's [terribly inefficient](https://www.warpconduit.net/2011/03/23/selecting-a-random-record-using-mysql-benchmark-results/). – Beowulfenator Nov 18 '15 at 00:07
  • @Beowulfenator got it thank you. I used the method in the conclusion on that article. – Mike Ross Nov 18 '15 at 00:11
  • Read the article. There are different solutions there and a graph that shows how they perform on different data sets. It is not relevant how many records you need to find, it's more important how many total entries you have in the table. – Beowulfenator Nov 18 '15 at 00:15

2 Answers2

32

Wrap it into yii\db\Expression to prevent escaping and remove array part:

use yii\db\Expression;

...

$query = User::find()
    ->where(['category_id' => 5])
    ->orderBy(new Expression('rand()'))
    ->limit(4);
arogachev
  • 33,150
  • 7
  • 114
  • 117
4

I'm not really an expert on yii2 query builder, however, specify the ordering should help

$data= User::find()->where(['category_id'=> 5])->orderBy(['rand()' => SORT_DESC])->limit(4);
Shadow
  • 33,525
  • 10
  • 51
  • 64