What is the equivalent to getLastInsertId() in Cakephp?

useranon picture useranon · Jun 11, 2009 · Viewed 118.7k times · Source

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:

function designpage() {
    //to create a form Untitled
    $this->Form->saveField('name','Untitled Form');
    echo $this->Form->getLastInsertId(); //here it works
}

function insertformname() {
    echo $this->Form->getLastInsertId(); //this doesnt echo at all
}

Please suggest a way to get the functionality I want.

Answer

nask0 picture nask0 · Apr 8, 2011

CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID(). Actually these methods are identical so it really doesn't matter which method you use.

echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();

This methods can be found in cake/libs/model/model.php on line 2768