I need to automatically generate API_KEY for each new User.
So I hook afterSave (because I need to know record ‘id’). From within afterSave() I generate and set ‘api_key’ property and call $this->save() - at which point it blows up with “Duplicate entry ‘6’ for key ‘PRIMARY’”.
When I try $this-update() instead - it blows up with "The active record cannot be updated because it is new". So how can I update/save record from within afterSave() ?
At the afterSave point the record still has the scenario ‘insert’ and so will always run an insert. You can either setScenario( ‘update’ ) and then call save. Or you can use updateAttributes(), iirc.