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?
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
Just try Class yii\helpers\Json;
$data = Youremodel::model()->find();
JSON::encode($data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With