2016-01-24 104 views
2

當我選擇的ActiveRecordyii2返回ActiveRecord的屬性作爲JSON與其他名

$models = Model::find() 
     ->select(['someothername' => 'name'])->all(); 

和這個「someothername」公共屬性添加到模型,然後我就可以訪問它

$model->someothername 

但現在我需要在JSON中返回此字段

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 
return $models; 

我該怎麼辦?我應該添加'someothername'屬性?

回答

1

嘗試覆蓋活動記錄中的fields()方法。

public function fields() 
{ 
    $fields = parent::fields(); 
    $fields['someothername'] = $this->someothername; 

    return $fields; 
} 

Docs about fields method

0

只是try類警予\幫手\ Json的;

$data = Youremodel::model()->find(); 
JSON::encode($data); 
相關問題