Updating link tables

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?

Anybody got any suggestions?

The only drawback is if there are many elements in the $this->genre array… in that case it would be faster to build an SQL INSERT command…

I was thinking in terms of a more elegant way to update the options - rather than delete them all and re-inserting some of the existing values. For example, for the following situation:

Current Values:

1, 2, 3, 4, 5, 6

New Values:

1, 3, 5, 7, 9, 11

What it should really do is:

  • delete the Values 2, 4, 6

  • keep the Values 1, 3, 5

  • add the Values 7, 9, 11

Then you need to remember the old values and compare them with the new ones… on the other side, there would be probably less deleting from the database…

It all depends on how frequently these options will be edited/changed…