Angeline
Angeline

Reputation: 2379

What is the correct way to write a find() statement in CakePHP given a simple select query with ORDER and LIMIT?

How to write this query using the find statement in cakephp

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

Upvotes: 1

Views: 3265

Answers (5)

Adriano Varoli Piazza
Adriano Varoli Piazza

Reputation: 7429

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.

Upvotes: 0

Alexander Morland
Alexander Morland

Reputation: 6434

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));
}

Upvotes: 0

Shiv
Shiv

Reputation: 8412

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.

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

This should do it:

$this->Form->find('all', array(
    'fields' => array('Form.id'),
    'order' => 'Form.id DESC',
    'limit' => 1
));

Upvotes: 5

dhofstet
dhofstet

Reputation: 9964

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

Upvotes: 0

Related Questions