CakePHP Model::save() resets fields to default values
I when I save (update) a field in a MySQL database via Model->save()
, if I do not specify a value for a field that has a default value set then it gets reset to the default.
This is doing this even if there is already a value for that field.
For example, consider this code:
$existing_user = $this->CustomCart->User->field('id',array('User.email'=>$this->data['User']['email']));
if($existing_user)
{
//update information
$this->CustomCart->User->id = $existing_user;
}
$this->CustomCart->User->save($this->data);
In this code, it checks to see if a user already exists with the passed email address. If so, update that user with the passed information, else create a new user.
However I have a field in the users table called role
the default value is customer
There is no value set for role
in $this->data
so when creating a new user the role
gets automatically set to customer.
However, when updating an existing user, even if they have something else for role like "admin"开发者_运维百科, it still resets the value to customer.
I do not know why this is. Other fields that I do not specifically set (that do not have a default value) maintain their values. So why do fields with default values get reset?
I got this one! You need to set this before save:
$this->CustomCart->User->create(false);
Without false Cake somehow guesses how model should look like.
I'll suppose that field() is a function that you've created to get a single field according to some conditions
how about this code?:
$existing_user = $this->CustomCart->User->field('id',array('User.email'=>$this->data['User']['email']));
if($existing_user !== false){
//update information
$this->CustomCart->User->id = $existing_user;
$this->data['User']['role'] = "admin";
}
$this->CustomCart->User->save($this->data);
i'd be really amazed if this code is not working correctly
Good Luck!
精彩评论