投稿の追加フォームでフィールドを取得し、スペースで展開し、各単語を HasAndBelongsToMany Post としてタグとして保存します。そのため、認識されないタグごとに新しいタグが作成されますが、タグが既に存在する場合は、posts_tags テーブルに新しい参照が作成されるだけです。saveAll、saveAssociated、およびいくつかの foreach ハックを使用してみましたが、どこで問題が発生したのか正確にはわかりませんが、関連データを保存する方法がわかりません。タグデータをフォームからデータベースに取得する方法の概要を教えていただければ幸いです。
//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'));
}