How to get an autoincremented id from a new model->save();


I have a simple model, just a few columns, but it uses an autoincrementing id that my database backend generated as needed.

What I need is a way to get that id, after I call ->save() on a new instance of my model.

$a = new Address;






$a->id;   // this is still null.


I thought about this:

  1. Generating a big 'ole complex GUID for the street field,

  2. Calling ->save(),

  3. Do a lookup on the GUID I used for the street,

  4. Now that I have a "real" record in my model object,

  5. Push my real data into the model object,

  6. Call ->update();

But that makes me feel dirty.

Is there another way to do this that seems less… hacky?


In your Model:


         * This is invoked after the record is saved.


        protected function afterSave()



                echo $this->id;


use this:

$id = $a->getPrimaryKey();

Small tip, I spend some time with a problem here.

I have a form to add/edit a model. The form has the pk field hidden.

If adding, this field is empty.

So when I do

model->attributes = $form

it puts the pk as ‘’

then when I do



the key was always ‘’

the autoincrement was working in the db as expected, but on save this does not get updated in the model.

so I add before the save




model->attributes = $form

and this works, when I save and getPrimaryKey it actually has the key.

It took me a while to understand though, that save does not update the model properties with the values in the db.




thanks Taro Uma, it work for me :D

One strange error I encountered related to this.

I had some code that was processing all the property values in the array before saving. it was also ‘processing’ the ‘id’ field (for no good reason other than it was included in all the other fields), which means the id field was getting set to an empty string (or null? not sure). The subsequent save() method worked no problem - and set the primary key ID field to the the next integer value (it was set to auto-increment) in the database. However, it did not replace the id value in the object in my php code with the new ID after the save. It was still set to the empty string (or maybe null - I can’t recall what value what in there) that I had put in there.

This was tough because the database values were correct, and there were no errors. But, I had no access (even after refresh) to the ID value.

Spent 20 minutes trying to find this, and thought it might help someone down the line.

Maybe you might have some post processing going on and it is modifying your model’s attributes.

We had same problem to, We resolve it by that way.

In our DB We have column SLUG is UNIQUE.

public function rules()


	[indent][/indent][indent][/indent]return array(


                    [indent][indent][indent][/indent][/indent][/indent][b][u]array('slug', 'unique'),[/u][/b]




Best Regards