Yii Framework Forum: active record and HAS_MANY relation - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

active record and HAS_MANY relation Rate Topic: -----

#1 User is offline   dimis283 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 277
  • Joined: 24-January 09

Posted 12 March 2010 - 03:39 AM

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', )
        );
    }

Posted Image
0

#2 User is offline   Shiki 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 26
  • Joined: 12-November 09

Posted 12 March 2010 - 04:42 AM

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....ign_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();
}

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users