2015-09-26 62 views
3

我是yii框架的新手。我只是試圖實現Restful API。在簡單的情況下(以下一些教程後)我已經成功了這一點:在yii中查詢後返回JSON

$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)然後我的問題是什麼是與relat編碼離子,什麼時候有用?

回答

1

創建JSON數據的Yii的方式前值編碼使用CJson庫

$query = "'select ' . $attributeNames . ' from device'"; 
$command = Yii::app()->db->createCommand($query); 
$result = $command->queryAll(); 

$ret = array_values($result); 

/* or ... 
    $ret = array(); 
    foreach ($models as $model) { 
     $ret = array(); 
     foreach ($attributeNames as $name) { 
      $row[$name] = CHtml::value($model, $name); 
     } 
     $ret[] = $row; 
    } 
*/ 

echo CJSON::encode($ret); 
Yii::app()->end(); 
1

我想你只需要回報

foreach ($models as $model) { 
    $row = array(); 
    foreach ($attributeNames as $name) { 
    $row[$name] = CHtml::value($model, $name); 
    } 
    $rows[] = $row; 
} 
return json_encode($rows); 
+0

感謝@scaisEdge,它被確實編碼,看到我的更新。 –

+0

好,如果我的回答有幫助,請評價它 – scaisEdge

0

很簡單!只需在開始時在您的方法中添加此行 - \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;並正常執行其他代碼 。

例如

public function actionHospitals() 
{ 
    \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON; 
    $hospitals = Hospitals::find()->select('speciality')->distinct()->all(); 
    return ['hospitals' => $hospitals]; 
}