active record and HAS_MANY relation

I have a table categories and another table articles that has artticles for the categories.

I want when a category is deleted to delete all articles for this category.

How can I do it at afterdelete function?


//cats 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('art'=>array(self::HAS_MANY, 'arts', 'cat_id', )

        );

    }

You could probably set this up in your database by using Referential Actions in your "cat_id" foreign key (i.e. Cascade Delete) http://en.wikipedia.org/wiki/Foreign_key#CASCADE

Or if this is impossible for your setup (maybe you’re using MyISAM), you could override the afterDelete method in your “cats” model:


// warning: untested because I use the Cascade Delete method ^_^x

// cats model

protected function afterDelete()

{

    // note: assuming cats.id is the primary key and arts.cat_id is the foreign key

    arts::model()->deleteAll('cat_id = :catId', array(':catId' => $this->id);

    parent::afterDelete();

}