tags:

views:

707

answers:

5

How to write this query using the find statement in cakephp

$this->Form->query("Select id from forms order by id DESC LIMIT 1")
A: 

Have a look at the documentation: http://book.cakephp.org/view/73/Retrieving-Your-Data

dhofstet
+5  A: 

This should do it:

$this->Form->find('all', array(
    'fields' => array('Form.id'),
    'order' => 'Form.id DESC',
    'limit' => 1
));
Paolo Bergantino
well, i get the value as "Array"
Angeline Aarthi
Angeline,You should a) read the documentation a little more and b) try a print_r ($variable); to see what's inside the array.
Travis Leleu
why did u mean this 'all' with limit 1? when thats what 'first' does?
Alexander Morland
find('all') and find('first') return different data structures. Technically 'first' will also do the job.
spoulson
@Alexander: Truthfully I haven't messed around with CakePHP for a while now (1.1) so I wasn't sure if 'first' had the LIMIT 1 implied or not. My original answer used it, but I figured it is better to be safe than sorry so I changed it to 'all' with the explicit limit.
Paolo Bergantino
A: 

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.

Shiv
you're missing a ' after ['Form
Adriano Varoli Piazza
A: 

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));
}
Alexander Morland
A: 

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.

Adriano Varoli Piazza