How to write this query using the find statement in cakephp
$this->Form->query("Select id from forms order by id DESC LIMIT 1")
How to write this query using the find statement in cakephp
$this->Form->query("Select id from forms order by id DESC LIMIT 1")
Have a look at the documentation: http://book.cakephp.org/view/73/Retrieving-Your-Data
This should do it:
$this->Form->find('all', array(
'fields' => array('Form.id'),
'order' => 'Form.id DESC',
'limit' => 1
));
I agree with the first response here, 2 things I would like to mention I assume you have a model called Form,Now Cakephp has its own FormHelper and sometimes there maybe a conflict of names, I got this error when I had created a FilesController in my project, Also you will get an array back which will be of the form
$result['Form] => array(
[id] => 1
[name] => whatever)
and so on, you can easily use this to get whatever data you want.
While this should be find('first'), the real issue is probably even simpler. I can only assume the only reason for doing such a query is to get the last inserted id. In the same "run" as a save you can get the inserted id in the model property by the same name:
$this->ModelName->create($this->data);
if ($this->ModelName->save()) {
$this->Session->setFlash('Saved it!');
$id_of_new_row = $this->ModelName->id;
$this->redirect(array('action' => 'view',$id_of_new_row));
}
As paolo said, but adding 'recursive' to the query:
$this->Form->find('all', array(
'fields' => array('Form.id'), // just return the id, thank you
'order' => 'Form.id DESC', // sort the query result by id DESC
'limit' => 1, // gimme the top id
'recursive' => -1, // don't scan associated models in the query
));
but I'd also use
$this->Form->find('first', array(
'fields' => array('Form.id'),
'order' => array('Form.id DESC'),
'recursive' => -1,
)
);
Which is not much shorter, but is more expressive of what you want.
And I'd suggest you take care, because there's a form helper already, and confusion could happen. On the other hand, you use the $form variable in views, generally, while this is controller code.