Kostas Livieratos
Kostas Livieratos

Reputation: 1067

Save data to different model inside a controller

I have a CakePHP controller named ProjectsController (and it's model named Project) and a Settings model. Inside the ProjectsController, there is a settings function, where inside it I need to save data into the database using the Settings model. The function is the following:

public function settings($pid = null) {
        if($this->request->is('post')) {
            $this->loadModel('Settings');
            $this->request->data['Project']['id'] = $pid;
            if($this->Settings->save($this->request->data)) {
                $this->Session->setFlash(__('Settings successfully set.'));
                $this->redirect(array('controller' => 'projects', 'action' => 'view', $pid));
            } else {
                $this->Session->setFlash(__('Something went wrong! Please try again.'));
                $this->redirect(array('controller' => 'projects', 'action' => 'settings', $pid));
            }
        }
    }

But it always fails and returns Something went wrong!
I have also to say that the Settings model has a hasOne relationship with Projects

public $hasOne = 'Project';

This is my first time trying to achieve something like this so please help me and tell me what am I doing wrong here,why this is not working?

Thank you in advance!

Upvotes: 0

Views: 813

Answers (1)

yossi
yossi

Reputation: 3164

As far as i know, a save() call, will save only the model's data. a saveAll() call will save any related (flat, first level) model's data.

You can also try $this->Model->associatedModel->save()

Upvotes: 3

Related Questions