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'));
}
請?任何人? – tyjkenn