Isnewrecord In Aftersave And Saveattributes Alternative?

I got two questions:

  • It seems that isNewRecord === false in the afterSave() method, even if it’s actually a new row (it returns true in beforeSave()), why is this?

  • Is there a saveAttributes() alternative for Yii 2? I only see the update() method, but I want to save some values in the database, without calling the beforeSave(), afterSave() etc. methods, saveAttributes() in Yii 1.x worked great for that.

Yes, it is set to false right after the actual saving is done (oldAttributes are set to new ones also). I suppose there are some good reasons for that. Yet I agree that this is pretty inconvenient.


I already thought something like that, but indeed, would like to know the reason behind it!

updateAll works in this case, but i still expected there would be a function i could use on object-level (so i could call $this->updateAttributes([‘status’ => 3’]); for example, instead of calling the static updateAll method where i have to specify the where condition (id = 241) separately.

You can use the $insert parameter of the afterSave() method to determine if the record is new or not.

I’m not sure if we should bring back saveAttributes(). It was removed from 2.0 because we want more consistent behavior regarding AR saving (i.e., we don’t want some methods will cause beforeSave(), while some not.) If you don’t want to call beforeSave(), you may use updateAll as ORey suggested.

Oh i see indeed! Thanks for the tip.

That’s clear, it would be very nice though to see it back in Yii 2, in some cases it’s very handy if you just can save some attributes to your database without any validation, beforeSave() stuff and so on.

Why not use AR scenarios to have conditional validations. For ‘scenario-1’ you may have no rules attached when saving the model, while for ‘scenario-2’ you can set validation rules. The scenarios can be set in your model events or controller action.

Alternatively - I would suggest - using query/command builder (instead of using $model->save) to populate data in bulk directly to the table. This is if you still need to totally bypass AR model validation.