1

In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?

Example

//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);

If it is not possible, please suggest an alternate best method to implement it.

Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:

'formats' => [
               'application/json' => Response::FORMAT_JSON,  
             ], 

1 Answer 1

4

You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:

class Result extends \yii\db\ActiveRecord implements Arrayable
{
    public $dynamic;

    // Implementation of Arrayable fields() method, for JSON
    public function fields()
    {
        return [
            'id' => 'id',
            'created_at' => 'created_at',
            // other attributes...
            'dynamic' => 'dynamic',
        ];
    }
    ...

..in your action pass some dynamic values to your model, and return everything as JSON:

public function actionJson()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $model = Result::findOne(1);
    $model->dynamic = [
        'field1' => 'value1',
        'field2' => 2,
        'field3' => 3.33,
    ];

    return $model;
}

In result you will get JSON like this:

{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}
Sign up to request clarification or add additional context in comments.

2 Comments

It is working. Is it possible to do without declaring fields function in model class.
Unfortunately it's not possible if you use ActiveRecord.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.