我想在Post的添加形式中使用一个字段,在空格处展开它,并将每个单词保存为标记,HasAndBelongsToMany Post。因此,对于每个无法识别的标记,它将创建一个新标记,但如果标记已存在,则它将仅在posts_tags表中创建新的引用。我已经尝试过使用saveAll,saveAssociated和一些foreach hacks,我不确定它出错的地方,但我无法弄清楚如何保存关联数据。任何形式的如何从表单到数据库获取标签数据的概述将不胜感激。
//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 :(得分: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;