Is there way to delete all dependent records when deleting a record?

Hi everyone,

Is there a built in way to delete all dependent records when the record itself gets deleted?

I have users to have many posts. When the user gets deleted all their posts should get deleted. Can that be done automatically?

I suppose I could overwrite beforeDelete() to take care of this.

But having this automated would of course be preferred


You can do it in the database layer (if supported) using FKs and constraints.

It may be better to be handled in the DB layer, though this ‘referential integrity’ depends on the DBs and Engines.

For example, InnoDB for MySQL has this functionality while MyISAM for that does not.

MySQL@Wikipedia says;

I know that in many cases this is best handled directly in the database, also for performance reasons.

However, in my case the dependent records have some files attached which also have to be deleted. Also, there are some cases in my database where I’d rather use MyIsam than InnoDB.

Probably I’ll implement a behaviour that can be attached which is gonna take care of this.


Then, you should take care of the referential integrity yourself.

You could overload CActiveRecord.beforeDelete() and do the cleanup manually …

that’s probably what I’ll be doing


you should do that on db layer, using a foregin key with a ‘on delete cascade’ clause.