如何手动更新CakePHP中的连接表

时间:2009-10-20 15:30:13

标签: php database cakephp

我是CakePHP的新手。 我有两个表:联系人和标签,以及HABTM表contacts_tags。用户应该能够像人们在delicious.com中那样添加标签。他们在键入时会得到一个标签列表。他们也可以通过键入来添加新标签。我想检查标签表,看看哪些标签已经存在,哪些标签不存在。应将新标记添加到表中,并将插入ID附加到数组中。然后我想使用这些标记ID来更新contacts_tags表。而已。这些是我创建的两个函数:

 /**
this function checks for existing tags and creates new tags
@params string (of comma separated tags)
@return array (of IDs)
**/
function saveAndCreateTags($tags){
    $tags = explode(",", $tags); //create array of tags
    $idArray = array();
    foreach($tags as $tag) {
        $count = $this->find('count', array('conditions' => array('name' => $tag)));
        if($count === 0) {
            $this->create();
            if($this->save($tag)) {
            $idArray[] = $this->getInsertID();
            }
        }
        else {
            $idArray[] = $this->getID();
        }
    }
    return $idArray;
}

/**
this function updates the relational table
@params array (this array is returned by saveAndCreateTags function
@params int (id of the contact)
**/
function updateContactTagsTable($idArray, $contactId){
    foreach($idArray as $tagId) {
        $count = $this->ContactTag->hasAny(array('tag_id' => $tagId, 'contact_id' => $contactId));
        if($count === 0) {
            ();
            $this->ContactTag->save(array('contact_id' => $contactId, 'tag_id' => $tagId));
        }
    }       
}

$ this-> ContactTag-> hasAny,$ this-> ContactTag->创建,$ this-> ContactTag->保存工作正常...我错过了什么?

1 个答案:

答案 0 :(得分:0)

saving new tags with a post

上查看teknoid上的这篇文章