使用 CakePHP,我需要检索基本记录列表。没有连接或特殊的 CakePHP 结果格式,只是以下数据格式的基本记录数组:
[
{first_name: 'Matthew', last_name: 'Stafford', gender: 'male'},
{first_name: 'Jason', last_name: 'Hanson', gender: 'male'}
]
使用蛋糕模型执行此操作的最简单方法是什么?
通过正确的 MVC 分离,输出像这样的 JSON 格式的结果 看起来像这样:
控制器:
$people = $this->Person->find('all', array('conditions' => ...));
$this->set(compact('people'));
查看:
echo json_encode(array_map(function ($p) { return $p['Person']; }, $people));
我当前的解决方案是在AppModel中添加以下方法:
function selectAll($options = array()) {
$this->recursive = 0;
$result = $this->find('all', $options);
return Set::combine($result, "{n}.{$this->name}.{$this->primaryKey}", "{n}.{$this->name}");
}