user765368
user765368

Reputation: 20346

cakephp order by another model field in association

just one quick question about orderBy in cakePHP find operations. let's say I have 3 models associated with each other. When I do a find('all') cakePHP query on any of my 3 models, I get the results which also includes the data from the other 2 models. For example, let's say my models are:

1- User
2- School
3- Country

If I do $this->find('all') inside UsersController, because my three models are linked together I will get something like this:

Array
(
     [0] => Array
         (
              [User] => Array
                     (
                          [id] => 'the_auto_incrementing_id'
                          // other table columns 
                          [created] 'creation_date'
                          [modified] 'modification_date'
                     )
              [School] => Array
                     (
                          [id] => 'the_auto_incrementing_id'
                          // other table columns 
                          [created] 'creation_date'
                          [modified] 'modification_date'
                     )
              [Country] => Array
                     (
                          [id] => 'the_auto_incrementing_id'
                          // other table columns 
                          [created] 'creation_date'
                          [modified] 'modification_date'
                     )
         )
)

My question is this, although my find('all') query was initiated on the User model, is it possible to orderBy let's say the created field in the model School for example?

Please let me know if that's possible at all

Thank you

Upvotes: 1

Views: 1597

Answers (1)

Dave
Dave

Reputation: 29121

If you're trying to get all the related data from User, School, and Country, but sort by School.created (per your example), you can just run the query from the School model.

I assume you're in the Users controller - if so, it'd just be this:

$myData = $this->User->School->find('all', array('order'=>'School.created DESC'));

(no need to load the school model, since it's linked, - so you an just refer to it through the User model)

Upvotes: 1

Related Questions