1

I am trying to find all products in random order using pagination. But getting an unexpected result. This is my controller code:

$this->paginate = ['maxLimit' => 20];
$articlesData = $this->Products->find('all');
$articlesData->order('RAND()');
$articles = $this->paginate($articlesData);

So I get random result every time, this is the demand of the page. I have 200 products. Suppose first item is item-12 on page one then if I go to the next page and again go to the previous page then the first item should be item-12 but it changed randomly. Is there any solution for this?

I need pagination because products number going to be 1000 soon. And need random results because I don't want that user to see the same first product on the first page. The first product should be on the first page but not on the same location every time. Is there any way that I make paginated array of 20 items in random order?

All suggestions are welcomed.

USER1359
  • 13
  • 3
  • I don’t see any logic between random results and pagination. Why pagination, if you will occasionally see the same entries on different pages? – Salines Aug 29 '21 at 20:31
  • I need pagination because products number going to be 1000 soon. And need random results because I don't want that user to see the same first product on the first page. The first product should be on the first page but not on the same location every time. Is there any way that I make paginated array of 20 items in random order? – USER1359 Aug 30 '21 at 06:19

2 Answers2

0

Example of how to rearrange results in view template. In the controller select from the latest Articles, but in the template display these 20 results in a different place each time.

#Controller

$this->paginate = ['maxLimit' => 20];
$articlesData = $this->Products->find();
$articlesData->orderDESC('creates');
$articles = $this->paginate($articlesData);
$this->set(compact('articles'));

#template

foreach(shuffle($articles->toArray() as $article) {
    echo $article['name'];
}

https://www.w3schools.com/php/func_array_shuffle.asp

Salines
  • 5,674
  • 3
  • 25
  • 50
0

When you order them randomly, they are ordered randomly. Every page load will be a new random order. See this for an example of how to make the order predictable; you might seed the generator with the user ID for example, then the order will always be the same for a given user. Or with some combination of user details and the date to give them a different random order tomorrow. Or randomly generate a seed and then save that in the session to control the duration more precisely.

Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35