为多个模型cakephp保存多个记录

时间:2011-05-18 18:44:37

标签: cakephp associations save

嘿伙计们,经过漫长的一夜之后,我被困住了。

我正在创建一个应用程序,您可以动态创建食物菜单,并建立如下关系:菜单hasMany Widget,Widget hasMany WidgetItem(当然,WidgetItem属于Widget,Widget属于菜单)。

首先创建菜单,然后将用户重定向到addSectionsToMenu,我在其中设置了多个小部件(标题输入),分别包含多个项目(菜单项)。

我的小部件保存并附加到菜单上,但我的WidgetItems不保存。我确定我的模型设置正常,我花了2个小时来整理我的$ data结构。我只是觉得我需要在这里找到一些东西。

请帮忙!

谢谢,

〜哈利

function addSectionsToMenu($menu_id = null){
    $this->layout = 'admin';
    $this->set('menu_id', $menu_id);
    $this->set('menu', $this->Widget->Menu->findById($menu_id));
    if (!$menu_id && empty($this->data)) { $this->Session->setFlash(__('Pick a menu to add to please :)', true)); }

    $saveSuccess = false;

    if(!empty($this->data['Widget'])) {
        $widget_count = 0;
        foreach($this->data['Widget'] as $widgetKey => $widget) : 
            if($this->Widget->saveAll($widget)) : $saveSuccess = true; endif;
            $widget_count++;
        endforeach;

        if ($saveSuccess) {

            $this->Session->setFlash(__($widget_count.' sections have been added to the Menu', true));
            $this->redirect(array('controller' => 'menus', 'action' => 'index'));

        } else {

            $this->Session->setFlash(__('The Menu and Sections could not be saved. Please, try again.', true));

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我在同时保存多个模型时遇到了问题,我通过调整验证选项解决了这个问题。

$this->Invoice->saveAll($this->data, array('validate' => true))

explanation of the options array对我来说没有任何意义,但默认情况下导致我的插入失败,因为相关记录没有从父记录的插入中获取其外键。将选项更改为“first”(默认值)为“true”解决了问题,并且行正确显示在数据库中。

相关问题