Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are multiple ways of doing this. One way is to use the afterFind-function in a model-class. See: <a href="http://book.cakephp.org/view/681/afterFind" rel="nofollow noreferrer">http://book.cakephp.org/view/681/afterFind</a>.</p> <p>BUT, this function does not handle nested data very well, instead, it doesn't handles it al all! Therefore I use the afterfind-function in the app_model that walks through the resultset</p> <pre><code>function afterFind($results, $primary=false){ $name = isset($this-&gt;alias) ? $this-&gt;alias : $this-&gt;name; // see if the model wants to attach attributes if (method_exists($this, '_attachAttributes')){ // check if array is not multidimensional by checking the key 'id' if (isset($results['id'])) { $results = $this-&gt;_attachAttributes($results); } else { // we want each row to have an array of required attributes for ($i = 0; $i &lt; sizeof($results); $i++) { // check if this is a model, or if it is an array of models if (isset($results[$i][$name]) ){ // this is the model we want, see if it's a single or array if (isset($results[$i][$name][0]) ){ // run on every model for ($j = 0; $j &lt; sizeof($results[$i][$name]); $j++) { $results[$i][$name][$j] = $this-&gt;_attachAttributes($results[$i][$name][$j]); } } else { $results[$i][$name] = $this-&gt;_attachAttributes($results[$i][$name]); } } else { if (isset($results[$i]['id'])) { $results[$i] = $this-&gt;_attachAttributes($results[$i]); } } } } } return $results; } </code></pre> <p>And then I add a _attachAttributes-function in the model-class, for e.g. in your Person.php</p> <pre><code>function _attachAttributes($data) { if (isset($data['first_name']) &amp;&amp; isset($data['last_name'])) { $data['full_name'] = sprintf("%s %s %s", $data['first_name'], $data['last_name']); } return $data; } </code></pre> <p>This method can handle nested modelData, for e.g. Person hasMany Posts then this method can also attachAttributes inside the Post-model.</p> <p>This method also keeps in mind that the linked models with other names than the className are fixed, because of the use of the alias and not only the name (which is the className).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload