Wednesday, March 2, 2022

[FIXED] Order by specific field values in CakePHP

Issue

I have array $productsTop

(int) 0 => '6
(int) 1 => '4',
(int) 2 => '1',
(int) 3 => '2',
(int) 4 => '3',
(int) 5 => '5'

where 6 4 1 2 3 5 are id's of product table. I want to display only 5 products from my products table but not order by ID ASC or DSC, I want to order them by ID exactly like they are ordered in arrar so it can first show product ID 6, then ID 4... to ID 5.

Can anybody help please.

$productTop = [6,4,1,2,3,5];

$product = $this->Product->find('all', array(
    'conditions'=>array('Product.id'=>$productTop),
    'limit'=>5
    ));

In this way it shows me all products but ordered by their ID so instead of showing me:

6,4,1,2,3,5

it shows:

1,2,3,4,5,6

Solution

You can order by specified values like this:

'order' => "FIELD(id, '6', '4', '1', '3', '2', '5')"


Answered By - Dave

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.