2012-05-16 4 views
0

게시물의 추가 양식에서 필드를 가져 와서 공백에서 분해하고 각 단어를 태그로 저장하고 싶습니다.이 필드는 HasAndBelongsToMany Post입니다. 따라서 인식 할 수없는 각 태그에 대해 새 태그를 만들지 만, 태그가 이미있는 경우에는 posts_tags 테이블에 새로운 참조 만 만듭니다. 나는 saveAll, saveAssociated 및 foreach 해킹을 사용하지 않으려 고 시도했지만, 어디서 잘못되었는지는 정확히 알 수는 없지만 관련 데이터를 저장하는 방법을 알 수는 없습니다. 양식에서 데이터베이스로 태그 데이터를 가져 오는 방법에 대한 모든 종류의 개요가 감사하겠습니다.HAB ™ 태그를 분할하는 방법은 무엇입니까?

//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; 
관련 문제