/** * afterFind callback * * @param Model $Model Model using this behavior * @param mixed $result The results of the find operation * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association) * @return void */ public function afterFind(Model $Model, $result, $primary) { // we only want to retrieve tags if the model was queried directly if (!$primary) { return $result; } // pre-process result to find which collections we need to lookup $tag_collection_ids = array(); foreach ($result as $row) { if (isset($row[$Model->alias][self::TAG_FOREIGN_KEY])) { $id = $row[$Model->alias][self::TAG_FOREIGN_KEY]; $tag_collection_ids[$id] = true; } } $tag_collection_ids = array_keys($tag_collection_ids); // fetch the tags from the db $tags_for = $this->TagCollection->findAllTagsFor($tag_collection_ids); // augment the result set with tags foreach ($result as &$row) { $row['Tag'] = array(); if (isset($row[$Model->alias][self::TAG_FOREIGN_KEY])) { $id = $row[$Model->alias][self::TAG_FOREIGN_KEY]; $row['Tag'] = isset($tags_for[$id]) ? $tags_for[$id] : array(); } } return $result; }