0

我想在帖子的添加表单中取一个字段,在空格处展开,并将每个单词保存为标签,即 HasAndBelongsToMany Post。因此,对于每个无法识别的标签,它都会创建一个新标签,但如果该标签已经存在,它只会在 posts_tags 表中创建一个新引用。我尝试过使用 saveAll、saveAssociated 和一些 foreach hack,但我不确定哪里出了问题,但我不知道如何保存关联数据。任何关于如何将标签数据从表单获取到数据库的大纲都将不胜感激。

//in model
public function parseTags($data) {
    $str = $data['Tag'][0]['title'];
    $tags = explode('',$str);
    for ($i=0; $i<count($tags); $i++) {
        $data['Tag'][$i]['title'] = $tags[$i];
    }
    return $data;
}

//in view
echo $this->Form->input('Tag.0.title',array('label'=>'Tags'));

//in controller
public function add() {
    if ($this->request->is('post')) {
        $this->Question->create();
        $this->request->data['Question']['user_id'] = $this->Auth->user('id');
        $this->request->data = $this->Question->parseTags($this->request->data);
        if ($this->Question->saveAll($this->request->data)) {
            $this->Session->setFlash(__('The question has been saved'), 'default', array('class' => 'success'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The question could not be saved. Please, try again.'));
        }
    }
    $users = $this->Question->User->find('list');
    $this->set(compact('users'));
}
4

1 回答 1

0

你必须先检查Tag之前是否保存过,如果没有保存,你可以保存它。因此,在您保存模型之前,您的所有标签都已保存。

像这样的东西:

/* $tag_list is exploded tags*/

        foreach ($tag_list as $tag) {
            $res = $this->Tag->find('first', array('conditions' => array('Tag.name' => $tag)));
            if ($res != array()) {
                $tag_info[] = $res['Tag']['id'];
            } else {
                $this->Tag->create();
                $this->Tag->save(array('Tag.name' => $tag));
                $tag_info[] = sprintf($this->Tag->getLastInsertID());
            }


        }
        $this->model->data['Tag']['Tag'] = $tag_info;
于 2012-08-18T17:45:38.933 回答