问题
Iam trying to save value '1' to the 'profile_created' field of my user table when the currently logged in user creates/adds a profile, my current implementation doesnt change this value, any suggestions? Thanks in advance.
Current profile adding code:
public function add() {
if ($this->request->is('post')) {
$this->Profile->create();
$this->request->data['Profile']['user_id'] = $this->Auth->user('id');
// code implemented below
$this->loadModel('User');
$data = array(
'Profile' => array('user_id' => $this->Auth->user('id')),
'User' => array('profile_created' => '1'),
);
if ($this->Profile->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('Your account profile has been created'));
$this->redirect(array('controller' => 'events', 'action' => 'index'));
} else {
$this->Session->setFlash(__('Your account profile could not be saved. Please, try again.'));
}
}
}
回答1:
You can't change values in $this->request->data
You're also creating $data and not using it anywhere
Try something like this (not tested of course)
if ($this->request->is('post')) {
$this->Profile->create();
$data = $this->request->data;
$data['Profile']['user_id'] = $this->Auth->user('id');
// code implemented below
$this->loadModel('User');
if ($this->Profile->save($data)) {
//Update user here if Profile saved successfully
$this->Profile->User->id = $this->Auth->user('id');
if($this->Profile->User->saveField('profile_created', '1')){
$this->Session->setFlash(__('Your account profile has been created'));
$this->redirect(array('controller' => 'events', 'action' => 'index'));
}else{
$this->Session->setFlash(__('Your Profile was saved, but an error has occurred while updating the Users table'));
//Email your self the user ID here or something ??
}
} else {
$this->Session->setFlash(__('Your account profile could not be saved. Please, try again.'));
}
}
Let me know if you need further help !
来源:https://stackoverflow.com/questions/16999502/saving-data-to-user-model-from-profile-model-cakephp