Changing A Model's Reference Variable

Hi there! I want to know if there is a cleaner solution for what I did. I needed to randomize an array in a model, so I did something like this at first:




shuffle($model->questions);



In this case, the model has a One to Many relation to a table named questions, making $model->questions an array to play with. I needed to randomize those questions in some specific case, like:




if($model->random_questions){

     shuffle($model->questions);

}



But PHP throws an “Indirect modification of overloaded property “X” has no effect” error, supposedly because it can’t get the ->questions value, it gets only the reference, and shuffle can’t modify by reference (or so I understood). So what I did was:




 if($model->random_questions){

    $questions=$model->questions;

    shuffle($questions);

    $model->questions=$questions;

}



It works just fine, but I really don’t like the roundabout way of doing it. Is there a cleaner way to do it? Or some way to make shuffle work fine with $model->questions, like in my first example?

If you don’t need to keep shuffling the the models you might look into the SQL ‘ORDER BY RANDOM’ statement. Not sure of your requirements, but should work for a one-shot pull of information. For a test that they cane start-pause-start, you’d have to store the answered Qs. So when they return, and a WHERE isNotAnswered clause with the RANDOM.

That’s a good point. I’ll see if I can incorporate it into my query.

Currently I do something like:




$model=Poll::model()->findByPk($id, array('with'=>array('questions'), 'order'=>'numeration'));



I will probably mess around with the array that manages the relations, or just build up a criteria object and change the order clause with a PHP if. As long as the code is simpler, and I would at least save processing by not going through the array shuffle.

Thanks for the suggestion!