【发布时间】:2015-12-24 06:25:13
【问题描述】:
我是 yii 框架的新手。我只是想实现 Restful API。在简单的情况下(在遵循一些教程之后)我已经成功了:
$result = [];
foreach($this->getData() as $record) {
$result[] = $record->getAttributes();
}
return $result;
请注意,getData() 是一个内置方法。在尝试将查询用于更高级的场景时,它是通过这种方式完成的:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
$attributeNames = explode(',', $attributeNames);
$rows = array();
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return $rows;
这是从查询结果中返回获取 JSON 的最佳做法,还是可以以更好的方式完成?
更新:
从以下方法返回最终响应:
private function sendAjaxResponse(AjaxResponseInterface $interface)
{
$success = count($interface->getErrors()) === 0;
$responseCode = $success ? 200 : 404;
header("content-type: application/json", true, $responseCode);
echo json_encode([
'success' => $success,
'data' => $interface -> getResponseData(),
'errors' => $interface -> getErrors()
]);
Yii::app()->end();
}
我发现只有这几行就足够了:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
return $models;
另一部分(嵌套循环)似乎是用关系编码(see here)那么我的问题是什么是用关系编码,什么时候有用?
【问题讨论】: