Empty values after ActiveRecord inheritance

  1. There is model

class Country extends ActiveRecord{

    public static function tableName()

    {

        return 'countries';

    }

}

  1. Trying to extend ActiveRecord with method getDataProvider()

class ActiveRecordEx extends ActiveRecord {

    public function getDataProvider($pageSize=20){

        $options = ['query' => static::find()->asArray()];

        if($pageSize)

            $options['pagination']= ['pageSize' => $pageSize];

        return new ActiveDataProvider($options);

    }

}

and use it


class Country extends ActiveRecordEx{…}

All works fine:


$dictionary = new Country();

$dataProvider = $dictionary->getdataProvider();  //is usable for data widgets

$model = $dictionary->findOne(['id'=>$recId]);  // $model has all db table attributes

  1. But when some of public Country attributes is defined it becomes inaccessible in model.

For example, after declaring id:


class Country extends ActiveRecordEx{

    public $id;

    public static function tableName() {…}

}

$model = $dictionary->findOne(['id'=>$recId]);  // $model->id is null

Debugger shows that all attributes (include id) have correct values in yii\db\BaseActiveRecord->_attributes.

Environment is Yii 2.0.3 on PHP 5.5.23.

What is correct way to use model attributes?

I’m not sure if I understand what is the problem here. It looks like you are defining virtual attribute $id for a model that has got the ‘id’ column in the database ([‘id’=>$recId]) and because of that you are resetting its value to null (public $id;).

Remove all declarations for the attributes that are present in database and check $model->XXXX again.

Exactly. Thank you for reply. I understood, this is usual behavior.

This was my fault because original models (like Country in example) were inherited from Model not from ActiveRecord and they still have own attributes.

No problem. Glad I could help. In case of any question don’t hesitate to ask - this is very friendly forum ;)