在我的应用程序中有3种类型的信息:
用户应在将所有数据保存到数据库之前填写所有数据。
我到目前为止所尝试的内容如下,但事务有问题,例如在没有BrokerBank记录的情况下创建BrokerInfo记录。存储一切或什么都没有的正确方法是什么?
public function add() {
if ($this->request->is('post')) {
$this->BrokerInfo->begin();
$this->BrokerInfo->create();
$this->request->data['BrokerInfo']['id'] = String::uuid();
$this->request->data['BrokerInfo']['account_status_id'] = 1;
$this->request->data['BrokerInfo']['db_status_id'] = 1;
if ($this->BrokerInfo->save($this->request->data)) {
$this->BrokerBank->begin();
$this->BrokerBank->create();
$this->request->data['BrokerBank']['broker_info_id'] = $this->request->data['BrokerInfo']['id'];
if($this->BrokerBank->save($this->request->data))
{
$this->BrokerDocument->begin();
$this->BrokerDocument->create();
if($this->BrokerDocument->save($this->request->data))
{
$this->BrokerInfo->commit();
$this->BrokerBank->commit();
$this->BrokerDocument->commit();
$this->Session->setFlash(__('The Broker information has been saved'), 'flash_success');
$this->redirect(array('action' => 'index'));
}
else
{
$this->BrokerInfo->rollback();
$this->BrokerBank->rollback();
$this->BrokerDocument->rollback();
$this->Session->setFlash(__('The customer information could not be saved. Please, try again.'), 'flash_fail');
}
}
else
{
$this->BrokerInfo->rollback();
$this->BrokerBank->rollback();
$this->Session->setFlash(__('The customer information could not be saved. Please, try again.'), 'flash_fail');
}
}
else
{
$this->BrokerInfo->rollback();
$this->Session->setFlash(__('The customer information could not be saved. Please, try again.'), 'flash_fail');
}
}
答案 0 :(得分:1)
问题中的代码是已经存在的东西的用户土地实现:saveAssociated
Model :: saveAssociated(array $ data = null,array $ options = array())
用于一次保存多个模型关联的方法。
使用saveAssociated
问题中的代码不过是:
public function add() {
if (!$this->request->is('post')) {
return;
}
$this->BrokerInfo->create();
$this->request->data['BrokerInfo']['account_status_id'] = 1;
$this->request->data['BrokerInfo']['db_status_id'] = 1;
if ($this->BrokerInfo->saveAssociated($this->request->data)) {
$this->Session->setFlash(...);
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(...);
}
请注意,没有必要指定uuid(在保存后使用$model->id
来引用新的id),并且当前的硬编码默认值最好放在模型beforeSave方法中,除非它们的值是控制器 - 逻辑依赖。