Gold Apple Software Web Development by Geoff Appleby

CakePHP

CakePHP HasOne - BelongsTo Relationship Keys

The common pattern in CakePHP is to give each table a Primary, Auto Incrementing `id` column, but when utilizing HasOne and BelongsTo relationships between two models this column is superflous and can make tracing downstream relationships more difficult. For example, when splitting data between User and Profile models, giving the profile it's own `id` column adds no useful information since the `user_id` column will by definition be a unique reference to a user.  The auto increment values may remain in sync and give you two columns of duplicate data, but if they diverge models related to the profile (e.g. ProfilePhoto) now lose their direct association with the user model. It is relatively easy though to modify the models and clean things up.

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).

Syndicate content