Php yii2将ActiveRecord属性作为JSON返回,并使用其他名称
当我选择ActiveRecord时Php yii2将ActiveRecord属性作为JSON返回,并使用其他名称,php,json,api,activerecord,yii2,Php,Json,Api,Activerecord,Yii2,当我选择ActiveRecord时 $models = Model::find() ->select(['someothername' => 'name'])->all(); 然后将这个“someothername”作为公共属性添加到模型中,我就可以访问它了 $model->someothername 但是现在我需要用JSON返回这个字段 \Yii::$app->response->format = \yii\web\Response::F
$models = Model::find()
->select(['someothername' => 'name'])->all();
然后将这个“someothername”作为公共属性添加到模型中,我就可以访问它了
$model->someothername
但是现在我需要用JSON返回这个字段
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $models;
我怎么做?我应该在属性中添加“someothername”吗?尝试覆盖活动记录中的
fields()
方法
public function fields()
{
$fields = parent::fields();
$fields['someothername'] = $this->someothername;
return $fields;
}
只需类yii\helpers\Json
$data = Youremodel::model()->find();
JSON::encode($data);