wouter
wouter

Reputation: 247

Correct way to define order in CakePHP 2

I have a CakePHP 2 (version 2.10.5) query that joins 2 tables, let's say I query on Model1 and join Model2 and Model3. I want to order my data by Model2.field_1 and Model3.field_2.

When I use this way:

'order' => ['Model2.field_1', 'Model3.field_2']

Or this way:

'order' => ['Model2.field_1' => 'ASC', 'Model3.field_2' => 'ASC']

Only the Model2.field_1 is added to the order part of the query.

When I use this way:

'order' => 'Model2.field_1, Model3.field_2'

Both fields are added to the order part of the query, they are quoted and everything so CakePHP interprets them correctly.

Why is this? And what is the correct way?

Upvotes: 1

Views: 236

Answers (1)

drmonkeyninja
drmonkeyninja

Reputation: 8540

Your first two examples should be the correct way of using order in CakePHP 2. You'll find examples of using order in the official docs under Retrieving Your Data.

So you should be either using:-

'order' => ['Model2.field_1', 'Model3.field_2']

Or:-

'order' => ['Model2.field_1' => 'ASC', 'Model3.field_2' => 'ASC']

Both would be interpreted the same. The documentation for Models explicitly describes the available formats for order.

I suspect that if these are not working in your query then there is another issue not shown here. I believe that when Cake is generating the query it will ignore order statements that aren't relevant to the query. For example, if you are trying to order on a has-many contain or you are using pagination and trying to order of a column that hasn't been configured correctly (see docs of pagination ordering).

Upvotes: 1

Related Questions