我有两张桌子,questions
and tags
,具有 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));
?>
首先确保您的模型设置正确。用户最初只向您的问题添加一个标签这一事实并不会改变您在问题模型和标签模型之间应该具有 HABTM 关系的事实(因为您希望以后可以添加更多标签)。
If your $this->data
数组是根据以下模式构建的:
$this->data = array(
'Question' => array(
'name' => 'Trick question'
),
'Tag' => array(
'Tag' => array(1,2,3)
)
);
Then a $this->Question->save()
将保存问题数据以及相关标签数据(在本例中为问题“Trick Question”,标签 ID 为 1、2 和 3)。
也许退后一步,(再次)烘焙这两个模型的模型、视图和控制器,看看 Cake 用它做出什么。如果我是对的,你只需要一个$this->Form->input('Tag')
表单中的某处(如果没有自动填写正确的数据,您需要填写options
参数与结果$this->Question->Tag->find('list')
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)