<?php

class ModelTag extends Fiktiv_Model_Abstract
{
    protected $_schema   = 'fiktivkod';
    protected $_name     = 'Tag';

    protected $_dependentTables = array('ModelPostTag');

    public function tagsToPost($tags, $postId)
    {
        $postsTags = new ModelPostTag();

        $postsTags->delete($this->quoteInto('postId = ?', $postId));
        
        foreach ($tags as $key => $tag) {
            $tags[$key] = trim($tag);

            if (empty($tags[$key]))
                continue;

            $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
            ));
            
        }
    }
}
