CakePHP HABTM表格提交

时间:2011-04-18 07:26:01

标签: cakephp

我有两个表,questionstags,它们具有HABTM关系。添加问题时,我希望能够为问题指定标记(这只是第一个标记,可以在以后添加更多标记)。标签从桌子上拉出来。如何配置我的应用程序,以便在添加问题并指定标记时,联接会反映在联接表(questions_tags)中?

以下是我的问题添加操作代码:

function add() {
    $tags = $this->Question->Tag->find('all');
    $this->set('tags',$tags);

    if (!empty($this->data)) {
        $this->Question->create();
        if ($this->Question->save($this->data)) {
            $this->Session->setFlash(__('The question has been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The question could not be saved. Please, try again.', true));
        }
    }
    $users = $this->Question->User->find('list');
    $tags = $this->Question->Tag->find('list');
    $this->set(compact('users', 'tags'));
}

这是我的问题添加视图代码:

<?php 
    echo $this->Form->create('Question');
    echo $this->Form->input('user_id',array('type' => 'hidden', 'value' => $this->Session->read('Auth.User.id')));
    echo $this->Form->input('title');
    echo $this->Form->input('details',array('type' => 'textarea'));
    echo $this->Form->input('tag_id');
    echo $this->Form->end(__('Submit', true));
?>

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

如果你有一个问题的标签,它不是HABTM。它必须是一对一或一对多的关系。

在您的问题模型中,您可以定义属性belongsTo:

class Question extends AppModel {
    var $name = 'Question';          
    var $belongsTo = array(
        'Tag' => array(
            'className'    => 'Tag',
            'foreignKey' => 'tag_id'            
        )
    );    
}

像这样。

这是一个描述如何设置HABTM的链接

HABTM

相关问题