Changes to Model:find('first') in CakePHP 2.3 Changes to Model:find('first') in CakePHP 2.3

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:


$user = $this->User->find('first', array('conditions' => array('id' => $id)));

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:


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

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

Published on Jan 30, 2013

Tags: CakePHP Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.