2012-05-16 73 views
0

我想在帖子的添加形式中添加一個字段,在空格處將其分解,並將每個單詞保存爲標籤,其中HasAndBelongsToMany Post。因此,對於每個無法識別的標籤,它將創建一個新的標籤,但是如果標籤已經存在,它將只在posts_tags表中創建一個新的引用。我試過使用saveAll,saveAssociated和一些foreach黑客,我不確定它出錯的地方,但我不知道如何保存關聯數據。值得讚賞的是如何從表單到數據庫獲取標籤數據的任何概述。如何拆分我的HABTM標籤?

//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')); 
} 
+0

請?任何人? – tyjkenn

回答

0

您必須先檢查標籤是否保存過,如果不保存,您可以保存。因此,在保存模型之前,您的所有標籤都已保存過。

是這樣的:

/* $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;