Preventing Unsafe Attributes From Being Saved

Hi. I have a model called Product, which has an attribute called total_price. The column total_price is automatically populated by the database using a trigger.

The problem is that if I do a $product->save(), the column total_price will be saved as well, which may lead to incorrect data being written in certain circumstances.

So far, the only way I have seen to prevent a column from being included in the save() is with something like this:


This works, but I need to remember to always save the product using the call above. Is there any better way of doing this, so I can do a $product->save() without having to worry about this?


In base ActiveRecord class

    public function updateByPk($pk, $attributes, $condition = '', $params = array())



        return parent::updateByPk($pk, $attributes, $condition, $params);


remove unsafe attributes for save(), update(), saveAttributes()

Hi Yan. Thanks, it’s a pretty nice one. I finally managed by extending beforeSave(), and unsetting the unsafe attributes, i.e:

protected function beforeSave() {


        unset($this->price_total); // We don't want price_total to be saved, as it's automatically updated by a DB trigger



But your approach is better and nicer :)