我想在帖子的添加表单中取一个字段,在空格处展开,并将每个单词保存为标签,即 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'));
}