Herokiller
Herokiller

Reputation: 2991

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?

Upvotes: 5

Views: 3804

Answers (2)

Max Sherbakov
Max Sherbakov

Reputation: 1955

Just try Class yii\helpers\Json;

$data = Youremodel::model()->find();
JSON::encode($data);

Upvotes: 1

Tony
Tony

Reputation: 5867

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

Upvotes: 2

Related Questions