adding related relational record on afterSave


I’ve trying to add a default related record on a relational active record class. I have defined the relations between two tables: “User” and “Profile” (using the MyISAM comment hack). Profile table maintains a foreign key that refers to “User” primary key called “id” (just as the example shown at the “Yii definitive guide”).

When a new user is registered (saved on table "User"), I would like to add a new row automatically to table "Profile" (only with the values of PK, which is an autoincrement, and FK, which refers to the new saved row), so that the next time the user wants to edit its profile, I populate the profile form appropiately from both tables.

I think that I could do it with an INSERT statement overriding the method "afterSave()" of the User ActiveRecord but… is there anyway to do it more elegant? I would like to use the corresponding method, as I just define the HAS_ONE relation as explained in the manual. But I only see advantages for reading relational data with find* methods.

I saw a method called “addRelatedRecord” but I really don’t know if it fits, and how to use it. Maybe I’m doing it more complex that it should, I’m just at the beginning of my yii adventure  ???.

Thanks  :D!

Overriding afterSave() is the right way to go (beforeSave and afterSave are like DB triggers). Do not use addRelatedRecord. As said in API, it is used internally for a different purpose.

Ok, thanks :). Anyway, answer myself better. I can use php code to do that, avoiding SQL statements, like the the code below in the afterSave() method for RegisterForm class:

class RegisterForm extends CActiveRecord {


    public function afterSave()


    	// Insert the related row in ProfileForm

		$profile = new ProfileForm();

		$profile->reg_id = $this->id;