Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent to getLastInsertId() in Cakephp?

Tags:

cakephp

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.

like image 266
useranon Avatar asked Jun 11 '09 06:06

useranon


4 Answers

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

like image 172
nask0 Avatar answered Nov 10 '22 12:11

nask0


Just use:

$this->Model->id;
like image 41
s razu Avatar answered Nov 10 '22 12:11

s razu


In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id

id - Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html

Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id

After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?

Can you explain the flow of your application and how it relates to your problem?

like image 22
Mike B Avatar answered Nov 10 '22 14:11

Mike B


You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?

If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.

like image 9
brettkelly Avatar answered Nov 10 '22 12:11

brettkelly