Gold Apple Software Web Development by Geoff Appleby

Code Snippets

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

Shortcut for cloning Drupal Git Repositories

Taken from a conversation on where several people shared some of their shortcuts for using git.  The following Bash function will clone a git repository from, and optionally set up and switch to a remote tracking branch of the specified version. 

Drop multiple MySQL tables

Since MySQL's DROP TABLE statement requires specifying each table you wish to drop, dropping many tables at once can be a pain; especially if you have InnoDB tables with foreign key constraints.  With the following stored procedure, tweaked from some of the helpful comments on the MySQL documentation, you can drop any tables matching a particular regular expression pattern.

Syndicate content