In my Profile model I have the following:
'genres'=>array(self::HAS_MANY, 'ProfileOption', 'profile_id', 'condition'=>'attribute_id=1'),
public function afterSave()
{
if(!empty($this->genres)) // $this->genres is the relation
{
foreach($this->genres as $genre)
{
$genre->delete();
}
}
foreach($this->genre as $genre) // $this->genre is the user-submitted checkbox array
{
$model=new ProfileOption;
$model->profile_id=$this->id;
$model->attribute_id=1;
$model->value=$genre;
$model->save();
}
return parent::afterSave();
}
In a nutshell what this does is updates the users ‘genre’ checkbox selections. It first finds any existing records for the profile and deletes them all. It then inserts a new set of records.
This of course works but I don’t particularly like this approach. Is there any better and efficient way of doing it?