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()?
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.
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.
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.
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.
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') ));
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')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With