【问题标题】:How do I split my HABTM tags?如何拆分我的 HABTM 标签?
【发布时间】:2012-05-16 04:28:51
【问题描述】:

我想在 Post 的 add 表单中取一个字段,在空格处展开它,并将每个单词保存为一个 Tag,即 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'));
}

【问题讨论】:

    标签: has-and-belongs-to-many cakephp-2.1


    【解决方案1】:

    你必须先检查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;
    

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2012-02-05
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多