有多种方法可以做到这一点。一种方法是在模型类中使用afterFind函数。 参见:http://book.cakephp.org/view/681/afterFind。
但是,这个函数不能很好地处理嵌套数据,相反,它并没有处理它! 因此,我使用一个afterFind功能在通过所述结果集行走app_model
function afterFind($results, $primary=false){
$name = isset($this->alias) ? $this->alias : $this->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->_attachAttributes($results);
} else {
// we want each row to have an array of required attributes
for ($i = 0; $i < 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 < sizeof($results[$i][$name]); $j++) {
$results[$i][$name][$j] = $this->_attachAttributes($results[$i][$name][$j]);
}
} else {
$results[$i][$name] = $this->_attachAttributes($results[$i][$name]);
}
} else {
if (isset($results[$i]['id'])) {
$results[$i] = $this->_attachAttributes($results[$i]);
}
}
}
}
}
return $results;
}
然后我添加_attachAttributes函数模型中的类,例如用于在你的Person.php中
function _attachAttributes($data) {
if (isset($data['first_name']) && isset($data['last_name'])) {
$data['full_name'] = sprintf("%s %s %s", $data['first_name'], $data['last_name']);
}
return $data;
}
该方法可以处理嵌套modelData,例如,人有许多帖子,那么这个方法也可以在Post模型中附加属性。
该方法也记住,由于使用别名而不仅仅是名称(这是className),所以具有除className之外的其他名称的链接模型是固定的。
这涵盖了需求。我继续这个元素。 – 2009-11-09 17:33:01