我想达到的是立即注册一个User和一个Firm。因此,我需要插入3个表:users、firms和firms_users。CakePHP应该自动这样做,因为我已经在模型中设置了$hasAndBelongsToMany聚合。但是在注册过程中,只编写users表。我是不是遗漏了什么?
注册表格
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('User.email', array('type' => 'email')); //standard HTML5 email validation
echo $this->Form->input('User.password');
echo $this->Form->input('Firm.0.name');
echo $this->Form->input('Firm.0.zipcode');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>User 模型的相关部分
public $hasAndBelongsToMany = array(
'Firm' => array(
'className' => 'Firm',
'joinTable' => 'firms_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'firm_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
),Firm 与模型的相关部分
class Firm extends AppModel {
public $hasAndBelongsToMany = array('User'=>array('className'=>'User'));终于实现了UsersController / show_reg_form动作
public function show_reg_form(){
if ($this->request->is('post')) {
$this->loadModel('Firm');
$this->User->create();
$this->Firm->create();
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('action' => 'loggedin','loggedin'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
}
}发布于 2014-05-21 11:22:01
我想这段代码能起作用
public function show_reg_form(){
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Firm->create();
if($this->Firm->save($this->request->data))
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('action' => 'loggedin','loggedin'));
}
else{
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
}
}
}发布于 2014-05-21 08:44:27
它应该是
echo $this->Form->input('Firm.name');
echo $this->Form->input('Firm.zipcode');发布于 2014-05-21 08:47:46
为了使用hasAndBelongsToMany关联进行保存,您应该有这样的数组来保存记录
Array
(
[User] => Array
(
[field_1] => 1
[field_2] => 2
[field_3] => 3
[field_4] => 4
)
[Firm] => Array
(
[0] => 5
[1] => 8
[2] => 4
)
)其中5,8,4是公司表的记录ids。
我想这不是你要找的情况,我建议你去看看
hasMany协会如果用户有很多公司public $hasMany = array('Firm');hasOne,public $hasOne = array('Firm');关联这样,当创建用户时,它将添加一个公司。
https://stackoverflow.com/questions/23778140
复制相似问题