Y
Y
yurygolikov2017-05-15 20:41:39
Yii
yurygolikov, 2017-05-15 20:41:39

Why is Yii2 ActiveRecord not populating object properties?

Yii2 ActiveRecord does not populate object properties.
That data obviously comes judging by the logs and the filled _attributes property, but if you access it like this: $model->id, then there is NULL. Why is that?
I suspect it's a matter of checks and rules. I tried to enter different validation rules, but did not understand what I was missing.
Thank you!
Simplified to reveal my error:
Sneaker Model

public $id;
public $param1;
public $param2;
public function rules()
{
   return [
       [['id', 'param1', 'param2'], 'safe']
   ];
}

Action
$model= Sneaker::findOne(2);
return $this->render('index', [
    'model' => $model,
]);

Table
id - INT
param1,param2 - VARCHAR

Model inference
app\models\Sneaker Object
(
    [id] => 
    [param1] => 
    [param2] => 
    [_attributes:yii\db\BaseActiveRecord:private] => Array
        (
            [id] => 2
            [param1] => 21
            [param2] => 22
        )

    [_oldAttributes:yii\db\BaseActiveRecord:private] => Array
        (
            [id] => 2
            [param1] => 21
            [param2] => 22
        )

    [_related:yii\db\BaseActiveRecord:private] => Array
        (
        )

    [_errors:yii\base\Model:private] => 
    [_validators:yii\base\Model:private] => 
    [_scenario:yii\base\Model:private] => default
    [_events:yii\base\Component:private] => Array
        (
        )

    [_behaviors:yii\base\Component:private] => Array
        (
        )

)

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
B
Boris Korobkov, 2017-05-15
@yurygolikov

Remove public properties from the model. The model will automatically make them itself based on data from the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question