trafalgar
trafalgar

Reputation: 736

How to find the latest record in cakephp?

I've got a a table with a column request_time. There will be multiple requests and I want to get the latest request of a particular username:

$this->Requests->find('all', 'conditions' => array (
                                               'username' => $username, 
                                               'MAX'=> 'request_time'));

The above doesn't work. Is there something in Cakephp or do I need to do my own ->query()?

Upvotes: 6

Views: 20498

Answers (2)

Arun Jain
Arun Jain

Reputation: 5464

You can use the following:

$this->Requests->find('first', array('conditions' => array('username' => $username), 
                               'order' => array('id' => 'DESC') ));

Where id is the auto incremented primary key. This will give you the latest (single) record, if you are using first in find method, or else use all instead.

If you are not using primary key, you can try the following:

$this->Requests->find('first', array('conditions' => array('username' => $username), 
                               'order' => array('request_time' => 'DESC') ));

Upvotes: 14

Moyed Ansari
Moyed Ansari

Reputation: 8461

If you have auto-incremented primary key then you find the latest record of this table try this

$this->Requests->find('find', 'conditions' => array ('username' => $username), 
                              'order' => array('id' => 'DESC') 
                      );

Upvotes: 3

Related Questions