Changes to Model:find(‘first’) in CakePHP 2.3

C

A new stable release of CakePHP has just been released a few days ago, version 2.3.  With this many great new changes have come out of it.  You can read the full change log here:
http://bakery.cakephp.org/articles/lorenzo/2013/01/28/cakephp_2_3_0_is_out

One of the things that immediately caught my mind was this great big bolded sentence:

IMPORTANT: Model::find('first') will now return an empty JavaScript array when no records are found. Make sure you update your tests!

Immediately after reading this I thought major code changes were going to be required; however, luckily my fear was unfounded.  Let me provide an example…

Here is a typical query that I would perform:

[code]
$user = $this->User->find(‘first’, array(‘conditions’ => array(‘id’ => $id)));
[/code]

Previously this function would return null if no results were found; however, no as you can see it will return an empty array.  After performing this function I would either in my controller or in my view execute the following code to detect if a user was found or not:

[code]
if ($user) {
// User found, do something
} else {
// No user found
}
[/code]

Have no fear, even after this subtle change, the code still works as expected. Next up you should checkout Organizing data with the jQuery Sortable plugin.

HOWEVER!

If your unit tests are asserting that the variable is null these will fail as it now must assert that count array is equal to 0.  Nice and simple, so remove panic 🙂

About the author

By Jamie

My Books