delete($this->quoteInto('postId = ?', $postId)); foreach ($tags as $key => $tag) { $tags[$key] = trim($tag); $tag = $this->fetchRow($this->quoteInto('name = ?', $tags[$key])); if (!$tag) { $tagId = $this->insert(array('name' => $tags[$key])); } else { $tagId = $tag->id; } $postsTags->insert(array( 'postId' => $postId, 'tagId' => $tagId )); } } }