Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 return ActiveRecord attribute as JSON with other name

When I select ActiveRecord

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

and add this 'someothername' as public property to the model, I can then access it

$model->someothername

But now I need to return this field in JSON

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

How can I do it? Should I add 'someothername' to attributes?

like image 680
Herokiller Avatar asked Oct 18 '22 17:10

Herokiller


2 Answers

Try to override fields() method in your active record.

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

    return $fields;
}

Docs about fields method

like image 154
Tony Avatar answered Oct 28 '22 21:10

Tony


Just try Class yii\helpers\Json;

$data = Youremodel::model()->find();
JSON::encode($data);
like image 26
Max Sherbakov Avatar answered Oct 28 '22 21:10

Max Sherbakov