Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php yii2将ActiveRecord属性作为JSON返回,并使用其他名称_Php_Json_Api_Activerecord_Yii2 - Fatal编程技术网

Php yii2将ActiveRecord属性作为JSON返回,并使用其他名称

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

当我选择ActiveRecord时

$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);