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

1 Answer 1

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;
        }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.