saveAssociated与belongsTo模型一起使用吗?我有 Donor
模型,该模型属于 User
模型。这意味着user_id
存储在Donor
模型中。我正在尝试使用saveAssociated()
在一次通话中保存捐赠者/用户数据。然而,这似乎不起作用
她是我尝试过的:
$this->request->data['User'][0]['role'] = 'donor'; //tried without the `[0]`
$this->request->data['User'][0]['activation_secret'] = $activation_secret;
if($this->Donor->saveAssociated($this->request->data, array('deep' => true))){
//success message
}
我这样做是为了解决这个问题:
$user = $this->Donor->User->save($this->request->data);
if(!empty($user)){
$this->request->data['Donor']['user_id'] = $this->Donor->User->getLastInsertId();
}
if($this->Donor->save($this->request->data)){
// success message
}
这是正确的方法吗?或者我错过了什么?
[编辑]
我的表单遵循此模式
<?php
echo $this->Form->create('Donor');
echo $this->Form->input('name', array('id' => 'name','div' => 'inline-input'));
echo $this->Form->input('surname', array('id' => 'surname','div' => 'inline-input'));
?>
NB。要保存的关联模型数据是硬编码的,如上面的保存操作中所示。
答案 0 :(得分:-1)
尝试以下方法:
$this->request->data['User']['role'] = 'donor';
$this->request->data['User']['activation_secret'] = $activation_secret;
unset($this->Donor->validate['user_id']); // This might solve your problem
if($this->Donor->saveAssociated($this->request->data, array('deep' => true))){
//success message
}