Active Record Random

Hello Friends

How Can I create a Random in active Record?

I Have 300 lines of data in my table and I need to show 30 lines on screen using random

Of course. Add to your controller:

        $model = Test::find()->asArray()->all(); // Fetching data as array

        $model = array_rand($model,30); // get 30 rendom items 

        return $this->render('test', ['model' => $model]);

In your view perform simple foreach. Goodluck :)

Thanks, works very well

For a huge database, it’s memory intense when calling all(),

an alternative method is to generate random keys first, and then retrieve relevant records

for ($count=0; $count<30; $count++){

    $keys[] = random_primary_keys();


//Generate Query with a long SQL in WHERE clause

$query = Test::find(); 

foreach($keys as $k){

   $query = $query->andWhere(  "id=$k" );  //calling andWhere 30 times in the loop


$models = $query->all(); //fetch only 30 records

just my 2 cents.

No bad :) But how will it work if the key doesn’t exist? For example: you have generated id like 1,2,3,4,5… But 1,5 was deleted from DB or id starts counting from 1000,1001… :)