Search code examples
phprestactiverecordyii2

Yii2 Rest Controller and public variable


I have made a REST controller with Yii2 framework. When I try to retrieve a record from my database through an ActiveRecord model, JsonFormatter give me only real attributes. How can configure JsonFormatter to give me also public variable? This is my code:

Controller

class MyController extends yii\rest\ActiveController
{
    ...

    public function actionView($id)
    {
        $struct = \common\models\Struct::find()->where(['id' => '285'])->One();
        if ($struct) {
            return $struct;
        }
        return false;
    }
}

Model

/**
* property string $id;
* property string $name;
*/
class Struct extends \yii\db\ActiveRecord
{
    public $test;
    ...
    public function afterFind()
    {
        parent::afterFind();
        $this->test = 'ok';
    }
}

result of request

{"id":1,"name": "ciccio"}

but if I print variable with print_r(), I have all object

\app\models\Struct object
(
    [test] => ok
    [_attributes:yii\db\BaseActiveRecord:private] => Array
    (
        [id] => 1
        [name] => ciccio
    )
)

How can I get the variable test property without add an empty field on my database table?


Solution

  • You can override the ActiveRecord::fields() method to add the custom field that is declared as the public property of the class. The fields() method returns the names of the columns whose values have been populated into this record.

    Looking at your code you are trying to set the test property inside the afterFind() and want that value to be reflected against all rows when you call the Model::find() method. If that is correct then add the following inside your model:

    public function fields() {
        $fields = parent::fields();
        $fields['test'] = 'test';
        return $fields;
    }
    

    Now when you call the \common\models\Struct::find() it will return

    {"id":1,"name": "ciccio","test":"ok"}