Need Clarification for afterFind()

Hi,

I am working on REST with Advance template.

I fetch only username and email field from user table, but result have status fields also .




// My Active Record Query

$model = User::find()->select(['username','email'])->one();




// AfterFind in user model





    public function afterFind()

    {

        parent::afterFind();

        $this->status = ($this->status == 0 ) ? "ACTIVE" : "INACTIVE";

        return true;

    }




and my JSON result is





{"username":"ilaiya","email":"abc@mail.com","status":"ACTIVE"}



If i remove the $this->status from afterFind() means it gives proper result.

And also have another doubt on afterFind()

when using fields().





    public function fields()

    {

        $fields = parent::fields();


        $fields['fullname'] = function($this){

            return $this->firstname . ' ' . $this->lastname;

        };


        return $fields;

    }

When loading user model from controller, output with fullname field.

But when i called it from another model afterFind(), it throws unknown column fullname.





// it throws error, [b]unKnown column fullname[/b]

public function afterFind()

    {

        parent::afterFind();

        $staff_name = function($data){

            $names = [];

            $model = User::find()->select(['fullname'])->where(['IN', 'id', $data])->all();

            foreach ($model as $key => $value) {

                $names[] = return $value->fullname;

            }

            return $names;

        };

        $this->subject_teacher = $staff_name($this->subject_teacher);

        return true;

    }

  1. Yes, your User model will always have a "status" attribute, even on partial selects, because it represents a row in table user (rather than a row in the result of an arbitrary select). yii\db\ActveQuery::asArray() can be used to fetch partial result.

  2. Fullname is defined as a PHP expression in your code so your DBMS has no idea what do you mean by "SELECT fullname".