how can I get random values from model?

This work … but if I add ‘order by’=>‘rand()’ dont work =(. I just need to get 3 random values from a table.




                                      <?php

                                        /* Prendo  */

                                        $modelllo = Automobili::model()->find(array(

                                          'select'=>'*',

                                          'limit'=>'3'

                                        ));

                                        echo $modelllo->marca;

                                      ?>



Maybe you have to add even in the select:

<?php

                                    /* Prendo  */


                                    &#036;modelllo = Automobili::model()-&gt;find(array(


                                      'select'=&gt;'*, rand() as rand',


                                      'limit'=&gt;'3'


                                      'order'=&gt;'rand'


                                    ));


                                    echo &#036;modelllo-&gt;marca;


                                  ?&gt;

Thank you =). Thank you very very much =).

A word of warning, order by rand() can be very inefficient, particularly for pulling one value out of a big table. The database needs to generate a random number for every entry in the table, which can mount up on a table with a lot of entries. The database then needs to sort the table based on this non-indexed value, which is inefficient also.

Generally, I’d expect you’d be better to do it as a couple of queries…

If you want an individual entry, or only a few, I’d suggest running the following:


$max = Table::model()->count();

$offset = rand(0,$max);

$model = Table::model()->find(array('offset'=>$offset));

You can repeat the second two steps to get multiple random items, noting that you may want to reduce $max by 1 each time and add an "TableID NOT IN ()" condition for previous selections.

The line is a little more blurred if you’re pulling out a lot of entries, and you may want to keep everything in SQL as there’s obviously going to be some overhead every time a connection is made. There’s a good page here describing how to select random entries purely in SQL:

ORDER BY RAND()