【问题标题】:Saving multiple records for multiple models cakephp为多个模型保存多条记录 cakephp
【发布时间】:2011-05-18 18:44:37
【问题描述】:

大家好,经过漫长的一夜,我被困住了。

我正在创建一个应用程序,您可以在其中动态创建食物菜单,并设置如下关系:Menu hasMany Widget,Widget hasMany WidgetItem(当然,WidgetItem belongsTo Widget,Widget belongsTo Menu)。

先创建菜单,然后将用户重定向到addSectionsToMenu,这里我设置了多个Widget(标题输入),分别有多个项目(菜单项)。

我的小部件可以保存并附加到菜单,但我的小部件不保存。我确信我的模型设置得很好,我花了 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));

        }
    }
}

【问题讨论】:

  • $this->Widget->validationErrors 的值是多少?将 config/core.php 中的 DEBUG 常量设置为 3 以查看使用 SQL 的完整调试和当前对象的转储。这两件事中的一件应该可以帮助您找出问题所在。

标签: cakephp associations save


【解决方案1】:

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

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

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

【讨论】:

  • 这里也一样。我有一个数据数组,我要像这样 $this->ExternalHeader->saveAll($data, array('validate' => true)) 一样传递到 saveAll 中。没有记录出现。我也卡住了。
猜你喜欢
  • 2011-05-14
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多