Silverstripe Version: 4.1
Question:
I’m trying to get a bunch of DB records into an array and then shuffle them.
I’ve truncated this code to just be one set of 3 questions, in reality I need to get 4 sets of random questions from different categories.
$allQuestions = Question::get();
$random = DB::get_conn()->random();
$questions = $allQuestions
->filter(['CategoryID' => 1, 'TypesID' => 1])
->sort($random)
->limit(3);
foreach ($questions as $question)
{
echo 'Question: '.$question->ID.'<br/>';
}
$questions->sort("rand()");
echo 'After shuffle <br/>';
foreach ($questions as $question)
{
echo 'Question: '.$question->ID.'<br/>';
}
Out put
Question: 5
Question: 2
Question: 4
After shuffle
Question: 5
Question: 2
Question: 3
Why has 4 changed to 3? I’m expecting to see the same 5,2,4 in a different order. I assume this is to do with SS ORM “lazy loading” but it was already looped in the first loop.
Do I have to use arraylist and all the non native stuff or?