0

投稿の追加フォームでフィールドを取得し、スペースで展開し、各単語を 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'));
}
4

1 に答える 1

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;
于 2012-08-18T17:45:38.933 に答える