0

In a CakePHP project, I have a User class and a Category class. A User hasMany 'Category' and Category belongsTo 'User'. When I create a user, I d like to create a coupla categories by default for the new user. But for some reason, only one new category gets created. What could I be doing wrong? This is the code I m using in the User's afterSave() function:

    function afterSave($created)
    {
        if($created):
            //create 2 categories 'Personal' and 'Work'
            $data1 = array(
                'Category' => array(
                    'user_id' => $this->id,
                    'name' => 'Personal',
                    'order' => 1
                )              
            );
            $d1 = $this->Category->save($data1);

            $data2 = array(
                'Category' => array(
                    'user_id' => $this->id,
                    'name' => 'Work',
                    'order' => 2
                )              
            );
            $d2 = $this->Category->save($data2); 
        endif;
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
walmik
  • 1,440
  • 2
  • 13
  • 30

1 Answers1

1

I think when you want to use save function more than one time you must use $this->Category->create(); before second save function.

      function afterSave($created)
        {
            if($created):
                //create 2 categories 'Personal' and 'Work'
                $data1 = array(
                    'Category' => array(
                        'user_id' => $this->id,
                        'name' => 'Personal',
                        'order' => 1
                    )              
                );
                $d1 = $this->Category->save($data1);

                $data2 = array(
                    'Category' => array(
                        'user_id' => $this->id,
                        'name' => 'Work',
                        'order' => 2
                    )              
                );
                $this->Category->create();
                $d2 = $this->Category->save($data2); 
            endif;
        }
Arash Mousavi
  • 2,110
  • 4
  • 25
  • 47