Milos Sretin
Milos Sretin

Reputation: 1748

Order by specific field values in CakePHP

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

Upvotes: 1

Views: 3244

Answers (2)

bugHunter
bugHunter

Reputation: 23

You can add like this. :)

->order(["FIELD(Product.id, '228')"=>'DESC', "Product.id"=>'DESC'])

Upvotes: 0

Dave
Dave

Reputation: 29121

You can order by specified values like this:

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

Upvotes: 6

Related Questions