Storing NULL values to database in CakePHP
After searching for a while, I was unable to find information on how to make sure CakePHP will store a NULL value to the database. If you unset the value from the data array sent to saveAll(), it will not be changed from its current value: this will suffice for saving new rows to the database if their default value is NULL, but it will not overwrite an existing value with NULL.
The solution is simple, just not described well: set the value of the data array item to null.
The following code snippet is from an instance where a user clears the value from a text field in order to remove the data. If unchanged an empty string would be stored instead of the desired NULL value (and would later cause errors due to a UNIQUE key constraint).
if (empty($data['Model']['item']) {
$data['Model']['item'] = null;
}
$this->Model->saveAll($data);

Comments
Post new comment