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

Her*_*ler 5 php api activerecord json yii2

当我选择ActiveRecord

$models = Model::find()
        ->select(['someothername' => 'name'])->all();
Run Code Online (Sandbox Code Playgroud)

并将这个“ someothername”作为公共属性添加到模型中,然后我可以访问它

$model->someothername
Run Code Online (Sandbox Code Playgroud)

但是现在我需要以JSON返回此字段

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $models;
Run Code Online (Sandbox Code Playgroud)

我该怎么做?我应该在属性中添加“ someothername”吗?

Ton*_*ony 2

尝试覆盖fields()活动记录中的方法。

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

    return $fields;
}
Run Code Online (Sandbox Code Playgroud)

有关 fields 方法的文档