Randy Hall
Randy Hall

Reputation: 8137

CakePHP add model name to information returned in queries

I want to include the model name in the returned results of a query using CakePHP's find() methods.

For instance, if I do a

$person = $this->Person->find("first", array(
    "conditions" => array (
        "Person.id" => $id
    )
));

I get back

Person{id:1, name:Abraham Lincoln}

I want to get back

Person{id:1, name:Abraham Lincoln, model: Person}

I'm fairly front-end oriented. I know I could loop through results and add these at the controller level, but that seems tedious, especially since most of my queries are far more complex, utilizing contain(). I imagine somewhere in CakePHP's core there's a place this kind of functionality could be added, I just don't know where.

Essentially, I'm looking for where CakePHP casts the database query to a php variable, so I can inject my additional model value.

I do know I will never use the column name "model" anywhere in my application. I'm also certain I want this information where I'm requesting it to be in every singe query, as little sense as it may make.

Upvotes: 2

Views: 102

Answers (1)

makallio85
makallio85

Reputation: 1356

Add this to every model where you need it:

public function afterFind($results, $primary = false) {
    foreach($results as $ikey => $item) {
        foreach($item as $skey => $subitem) {
            if(is_array($subitem))
                $results[$ikey][$skey]['model'] = $skey;
            else $results[$ikey]['model'] = $skey;
        }
    }
    return $results;
}

Unfortunately I wasn't able to get this work when I stored it in AppModel.

Upvotes: 2

Related Questions