Save many-to-many information

Hy guys, i need some advice for the following.

I have three tables: daytrip, daytrip_tag and tag. When saving (edit or add) a daytrip i need to save the new tags and the relation between the daytrip and tag.

What is the best approach…

i was thinking about an afterSave in the Daytrip model. But this will go wrong for tag that already excist for a daytrip… (Unique constraint violation)

    protected function afterSave() {

        foreach ($this->tags as $tag) {

            $find = Tag::model()->find('tag=:tag', array(':tag' => $tag));

            if (!$find) {

                $row = new Tag;

                $row->name = $tag;


                //insert using $this->id_daytrip and $row->id_tag

            } else { //tag already excist

                //insert using $this->id_daytrip and $find->id_tag

                //goes wrong for tags that already excist for daytrip




Collect this tabular input is not as easy as it looks like.

You have 3 options:

  • editing an existing tag

  • create a new tab

  • delete an existing tag

All this three options can be at one time.

Maybe you want to do some validation (avoid that a tag is saved twice).

I advice you this extension, you can use or take inspiration from his code.

I’d go for afterSave, too. Your logic could go like this:

  1. Check Tags
  • Find all Tag records where ‘tag IN(tag1,tag2,tag3)’

  • Filter out those tags that are not present in this result

  • Create a new tag for the missing ones

  1. Check DaytripTags
  • Find all DaytripTags where ‘daytrip_id=id AND tag IN(tag1,tag2,tag3)’

  • Filter out again those tags that are not present in this result

  • Create new DaytripTag relation records for these

You should need 2 findAll() queries. If you use 1.1.5 you could try the new index feature to easily find the missing tags in you result.