Delete Active Records With Relationship

I have two tables:




users{

id

username

password

}


person{

id

fname

lname

user_id

}



and relation in User model:




public function relations()

{

    // NOTE: you may need to adjust the relation name and the related

    // class name for the relations automatically generated below.

    return array(

        'person'=>array(self::HAS_ONE, 'Person', 'user_id'),

    );

}



In tutorial there was said I can delete both by writting in user controller:




$this->loadModel($id)->person->delete();



but it deletes only person record in db.

and if I write:




$this->loadModel($id)->with('person')->delete();



This deletes only user record in db.

How can I delete both using these relations or changing them perhaps?

Of course I could write that in 3 lines:




$user=$this->loadModel($id);

Person::model()->findByPk($user->person_id)->delete();

$user->delete();



and it would delete both.

If you’ve set your foreign keys constraints correctly in the database, the related records will be automatically deleted.

See here for more information.

Ideally, you should choose one to act as the main record (say, user), then always delete that record and let the person record be deleted by the foreign key constraints.

The constraint would be on the person table and would look something like this:




ALTER TABLE `person`

  ADD CONSTRAINT `person_user`

  FOREIGN KEY (`user_id`)

  REFERENCES `user` (`id`)

  ON DELETE CASCADE

  ON UPDATE CASCADE;