Ben Oberholzer Fri Jun 10 11:18:32 -0400 2011

Subject: Handling notFound exception

Using a direct query to mysql, I would first check to see if the query was successful and then check to make sure it returned at least one row.

How do I do that with this model? I've been doing things like:

$debug = Module::find('debug');
if(count($debug) > 0) {
// do something

But what happens if 'debug' gets removed from the database?

Daniel Lowrey Tue Jun 14 15:49:43 -0400 2011

When you load a record by its primary key a RecordNotFound exception is thrown if no result is returned. The following two methods are equivalent:

$debug = Module::find('debug');

// Same as above
$debug = Module::find_by_pk('debug');

So, assuming your model is named "Module" and you're searching for a record with the primary key value of "debug" you would do exception handling like so:

try {

$debug = Module::find('debug');
} catch (\ActiveRecord\RecordNotFound $e) {
echo 'Oh no! I'm a moron!';


Note the namespace declaration on the exception (\ActiveRecord\). If you're unfamiliar with namespaces this is necessary because the exception is in the ActiveRecord namespace. The PHP manual will tell you all you wanna know about namespaces:

In contrast, generating a query that may have multiple results will not throw an exception if no records are returned. You'll simply get an empty array. So, if the name of the primary key column in the "Module" model is "my_field" you could do the following and not see an exception:

$conds = array('my_field = ?', 'debug');
$results = Module::find(array('conditions'=>$conds));
foreach ($results as $row) {