What you can expect as $results in afterFind()

Function afterFind() can be called in various contexts with different types of $results. If you don’t handle them all properly the function will not work right (which you may not care in some cases) and you’ll end up with notice level errors.

Here are situations I stumbled upon, let me know if you have found some more:

  1. if your model contains a validation rule ‘isUnique’ then afterFind() gets called from $model->invalidFields() with a result of SELECT COUNT():
    array(array(array(‘count’ => 1)))
  2. another results scheme is yielded by a model association (e.g. via belongsTo):
    array(‘id’ => 123, ‘first_name’ => ‘Joe’…)
  3. and then there’s the regular $model->find() which gives
    array(
    0 => array(‘ModelName’ => array(‘id’ => 123, …)),
    1 => array(‘ModelName’ => array(‘id’ => 124, …))
    )

So what is the best way to work with this omnishaped variable?

First skip everything if there are no results:

  1. if (!count($results)) {
  2.   return $results;
  3. }

Then check for case 2 (assuming your primary key is ‘id’):

  1. if (isset($results[‘id’])) {
  2.   // do your thing
  3. }

then for case 3:

  1. elseif (isset($results[0][$this->alias][‘id’])) {
  2.   // do your thing
  3. }

and lastly you can check for the count result if you care:

  1. elseif (is_array($results[0][0]) && isset($results[0][0][‘count’])) {
  2.   // do your thing
  3. }

Leave a Reply