Tag Archives: UUID

CakePHP2 Find Neighbors Method with UUID Primary Keys

I recently decided to switch over an application I have been developing from using INT primary keys to use CakePHP’s ability to generate UUID primary keys. It wasn’t difficult to do, you simply set the primary key to BINARY(36) and Cake will do the rest. (the CakePHP manual recommends VARCHAR(36) or CHAR(36) however do a bit of reading and you’ll find that these are not the quickest)

That said there are always problems that you don’t foreseeĀ  as a result of a small change like this. The problem I faced was that records could no longer be sorted by id. As it was I generally don’t sort by id but by a unique field with a simple ASC or DESC sort. This works most of the time except when you want to find the previous or next record…

In one instance I was using the find by Neighbors method to create some simple NEXT and PREV links to move between records. The task is simple with the follow code when using INT as a primary key.

That works well with ID’s but not with UUID’s. So what can be done. Well you need another field in your model that you can sort your data by. This may mean that you have to create a “sort” field or perhaps like me you have a simple “date” field in your model. In my application this works well because I have only one date for each week of the year so I never have a record with the same date. Here’s the solution I eventually got working.

It requires an extra line of code. The magic findById method is used and then we can set the value of “value” to “$order[‘Model’][‘date’]” and set the “field” value to “date”.

This returns a nice array for you to use in your view.

A simple tidy solution to what at first seemed complicated.