title: Returning JSON after a query in yii
body: <p>I'm new to yii framework. I'm just trying to implement Restful APIs. In the simple case scenario (after following some tutorial) I've succeeded with this:</p>
  
  <pre><code>$result = [];
  foreach($this-&gt;getData() as $record) {
      $result[] = $record-&gt;getAttributes();
  }
  return $result;
  </code></pre>
  
  <p>Note that <code>getData()</code> is a built-in method. Where when trying to use queries for more advanced scenarios, it's done this way:</p>
  
  <pre><code>$attributeNames = 'udid,model,appverionid';
  $connection = Yii::app()-&gt;db;
  $command = $connection-&gt;createCommand('select ' . $attributeNames . ' from device');
  $models = $command-&gt;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;
  </code></pre>
  
  <p>Is that the best practice to return get JSON from queries results, or maybe it can be done in a better way?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>The final response is returned from the following method:</p>
  
  <pre><code>private function sendAjaxResponse(AjaxResponseInterface $interface)
  {
      $success = count($interface-&gt;getErrors()) === 0;
      $responseCode = $success ? 200 : 404;
      header("content-type: application/json", true, $responseCode);
      echo json_encode([
      'success' =&gt; $success,
      'data' =&gt; $interface -&gt; getResponseData(),
      'errors' =&gt; $interface -&gt; getErrors()
      ]);
      Yii::app()-&gt;end();
  }
  </code></pre>
  
  <p>And I found out that only these lines are sufficient:</p>
  
  <pre><code>$attributeNames = 'udid,model,appverionid';
  $connection = Yii::app()-&gt;db;
  $command = $connection-&gt;createCommand('select ' . $attributeNames . ' from device');
  $models = $command-&gt;queryAll();
  return $models;
  </code></pre>
  
  <p>The other part (the nested loop) seems for encoding with relations (<a href="http://learnyii.blogspot.com/2011/07/yii-json-cjson-models-model-related.html" rel="nofollow">see here</a>) Then my question is what is encoding with relations and when it is helpful?</p>