yiisoft / yii2-mongodb

Yii 2 MongoDB extension
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
326 stars 191 forks source link

$model->setAttributes() does not populate all properties #331

Closed set-killer closed 3 years ago

set-killer commented 3 years ago

What steps will reproduce the problem?

I have the following model declaration:

namespace app\modelsMongo;

use yii\mongodb\ActiveRecord;

class Test extends ActiveRecord {
    public static function collectionName() {
        return 'test-deleteme';
    }

    public function rules() {
        return [
            [['uuid'], 'required'],
        ];
    }

    public function attributes() {
        return [
            '_id',
            'uuid',
            'name', 
        ];
    }
}

After that i try to populate the model as follows:

$model = new Test();
$model->setAttributes([
    "uuid" => "aaa-bbb-ccc",
    "name" => "my name"
]);
$model->save();

As a result only the uuid property is filled into the database and the name property is missing. This is what's saved in the database:

  {
    "_id": {
      "$oid": "60211511bf439768de191e02"
    },
    "uuid": "aaa-bbb-ccc"
  }

Additional info

Q A
Yii version 2.0.40
Yii MongoDB version 2.1.11
MongoDB server version 4.0.11
PHP version 7.2
Operating system Linux
samdark commented 3 years ago

That is expected behavior. By default, only safe fields could be mass-assigned. Safe field is a field that either has a validation rule or explicitly marked with safe rule. In your case you don't have any validation rule for name thus it is considered unsafe to mass-assign it. If you're absolutely sure you can't have a validation rule for it you can do setAttributes($values, false).

set-killer commented 3 years ago

Okay, thank you.