我在舞者和舞蹈之间有HABTM关系。事情似乎按预期工作,除了在编辑我的舞蹈的edit.ctp上,CakePHP显示一个下拉框而不是我期待的多选框。令我发疯的是,多选框正在使用edit.ctp以编辑舞者的方式工作!我无法弄清楚为什么它会以某种方式工作,而不是另一种方式。
这是我的舞蹈模型,定义了舞蹈与舞者之间的关系:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasAndBelongsToMany associations
*
* @var array
*/
public $hasAndBelongsToMany = array(
'Dancer' => array(
'className' => 'Dancer',
'joinTable' => 'dancers_dances',
'foreignKey' => 'dance_id',
'associationForeignKey' => 'dancer_id',
'unique' => 'keepExisting',
)
);
这是我的舞蹈控制器:
public function edit($id = null) {
if (!$this->Dance->exists($id)) {
throw new NotFoundException(__('Invalid dance'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Dance->save($this->request->data)) {
$this->Session->setFlash(__('The dance has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The dance could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Dance.' . $this->Dance->primaryKey => $id));
$this->request->data = $this->Dance->find('first', $options);
}
$users = $this->Dance->User->find('list');
$dancers = $this->Dance->Dancer->find('list');
$this->set(compact('users', 'dancers'));
}
这是舞蹈视图的edit.ctp
<div class="dances form">
<?php echo $this->Form->create('Dance'); ?>
<fieldset>
<legend><?php echo __('Edit Dance'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('dance_name');
echo $this->Form->input('users_id');
echo $this->Form->input('Dancers');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('Dance.id')), null, __('Are you sure you want to delete # %s?', $this->Form->value('Dance.id'))); ?></li>
<li><?php echo $this->Html->link(__('List Dances'), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Dancers'), array('controller' => 'dancers', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Dancers'), array('controller' => 'dancers', 'action' => 'add')); ?> </li>
</ul>
</div>
我认为相关的表格是: 舞者, dancers_dances, 舞蹈
在dancers_dances表上,我有以下列: ID, dancer_id, dance_id
如果有更多信息可以提供帮助,请告诉我。
提前致谢。
答案 0 :(得分:4)
首先,您可以摆脱HABTM定义中的大多数设置,因为您已经使用了Cake Conventions;
public $hasAndBelongsToMany = array(
'Dancer' => array(
'unique' => 'keepExisting',
)
);
但问题出在表单内部输入的名称中,该名称应为单数,并以与其相关的模型命名;
echo $this->Form->input('Dancer');
您可以在此处查看手册中的一些示例(查找本节中的“标记”示例):
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm