Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the latest record in cakephp?

Tags:

mysql

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()?

like image 383
trafalgar Avatar asked Jul 03 '13 17:07

trafalgar


People also ask

How to find latest record in sql?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table.

How to fetch latest record from database?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How to get latest record in sql by date?

From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table. Select * From SampleTable Order By [Date] Desc; After executing the above example, the server will return the records in such a way that the records with the latest dates appear at the top.

How can I get data from cakephp?

To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.


2 Answers

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') ));
like image 170
Arun Jain Avatar answered Oct 21 '22 03:10

Arun Jain


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') 
                      );
like image 27
Moyed Ansari Avatar answered Oct 21 '22 04:10

Moyed Ansari