2016-01-24 35 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);