August 16, 2010, 9:36pm
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:
Generating a big 'ole complex GUID for the street field,
Do a lookup on the GUID I used for the street,
Now that I have a "real" record in my model object,
Push my real data into the model object,
But that makes me feel dirty.
Is there another way to do this that seems less… hacky?
August 16, 2010, 11:16pm
In your Model:
* This is invoked after the record is saved.
protected function afterSave()
August 17, 2010, 5:19am
$id = $a->getPrimaryKey();
September 26, 2014, 4:47pm
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.
November 6, 2014, 10:17am
January 10, 2015, 9:40am
thanks Taro Uma, it work for me
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.
February 23, 2015, 9:33pm
Maybe you might have some post processing going on and it is modifying your model’s attributes.
March 25, 2015, 7:35pm
We had same problem to, We resolve it by that way.
In our DB We have column
SLUG is UNIQUE.
public function rules()