开发者

Saving multiple records for multiple models cakephp

开发者 https://www.devze.com 2023-03-07 01:06 出处:网络
Hey guys, I\'msuper stuck after a long night. I\'m creating an app where you can create food menus dynamically, and have relationships set up as such: Menu hasMany Widget, Widget hasMany WidgetItem (

Hey guys, I'm super stuck after a long night.

I'm creating an app where you can create food menus dynamically, and have relationships set up as such: Menu hasMany Widget, Widget hasMany WidgetItem (and of course, WidgetItem belongsTo Widget, Widget belongsTo Menu).

The menu is created first, then the user is redirected to addSectionsToMenu, where I have set up multiple Widgets (title input), respectively with multiple items (menu items).

My widgets save and attach to the menu fine, but my W开发者_高级运维idgetItems don't save. My models are set up fine I am sure, and I spent 2 hours sorting out my $data structure. I just think I need to figure something out here.

Please help!

Thanks,

~Harley

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));

        }
    }
}


I've had problems saving multiple models at once and I solved it by adjusting the validation option.

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

The explanation of the options array doesn't make complete sense to me, but the default was causing my insert to fail because the related records were not getting their foreign key from the insert of the parent record. Changing the option to "first" (the default) to "true" solved the problem and the rows are showing up in the database correctly.

0

精彩评论

暂无评论...
验证码 换一张
取 消