cakephp保存其他模型数据

时间:2010-09-30 07:58:33

标签: cakephp forms

我有两个型号

休息(身份证,姓名.....)
Operating_hours(id,open,close,rest_id)

当我尝试从餐馆添加表单保存记录时。它只保存打开和关闭时间,但不保存rest_id中的引用ID。

$this->Restaurant->create();
if($this->Restaurant->saveAll($this->data, array('validate' => 'first'))) {
    $this->Session->setFlash(__('The restaurant has been saved', true));
    //$this->redirect(array('action' => 'index'));
} else {
    $this->Session->setFlash(__('The restaurant could not be saved. Please, try again.', true));
}

1 个答案:

答案 0 :(得分:2)

如果您正在进行插入(因为它是“添加”),您不可能一步完成所有操作,因为MySQL不知道您餐馆的ID以节省开放时间。我建议做以下事情:

$this->Restaurant->create();
if($this->Restaurant->save($this->data, array('validate' => 'first'))) {
    $this->data['rest_id'] = $this->Restaurant->getLastInsertId();
    if($this->Restaurant->OperatingHours->save($this->data, array('validate' => 'first'))) {
        $this->Session->setFlash(__('The restaurant has been saved', true));
        //$this->redirect(array('action' => 'index'));
    } else {
        $this->Session->setFlash(__('The restaurant opening hours could not be saved. Please, try again.', true));
    }
} else {
    $this->Session->setFlash(__('The restaurant could not be saved. Please, try again.', true));
}