Veiko
Veiko

Reputation: 1

Ordering in find()

I have a model Org. In a model Org I have $hasAndBelongsToMany = array('Patient','Project','Category'); In orgs controller action view I get data from database with $this->set('org', $this->Org->find('first',array('condition'=> array('id'=>$id)))); Result is ok but I want change the order. I want order result Patient by name, Project by name and Category by id. How use ORDER BY for Patient,Project,Category in find() ?

Upvotes: 0

Views: 46

Answers (1)

Dan
Dan

Reputation: 1015

Assuming this is Cake, the ordering of associated models should be done in the model when you declare the HABTM relationship:

<?php
    class Org extends AppModel {
        var $hasAndBelongsToMany = array(
            'Patient' => array(
                'order' => array(
                    'Patient.name ASC'
                )
            ),
            'Project' => array(
                'order' => array(
                    'Project.name ASC'
                )
            ),
            'Category' => array(
                'order' => array(
                    'Category.id ASC'
                )
            )
        );
    }
?>

If you're wanting to sort the actual result set by the associated models you can pass an order array to the find method:

<?php
    $org = $this->Org->find('all', array(
        'conditions' => array(
            'Org.column_name' => $yourVar
        ),
        'order' => array(
            'Patient.name ASC',
            'Project.name ASC',
            'Category.id ASC'
        )
    ));
?>

If you're doing a find first by a unique field (like an ID) you can use the built in findByFIELDNAME helper:

<?php
    $org = $this->Org->findById($id);
    $this->set(compact(array('org')));

Upvotes: 1

Related Questions