Search code examples
phpyii2yii2-model

Custom Yii2 TimestampBehavior


I have behavior in my model

public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => time(),
        ],
    ]; 
}

Everything is working. But I need that only in one action does not work. It is necessary that in actionView did not change "update_at" attribute. My actionView:

$model = $this->findModel($id);
$model->views++;
$model->save();

How can I do this as correctly as possible?


Solution

  • Use:

    $model->save(false, ['views']);
    

    First parameter determines if validation should run (for this example it's not necessary), second determines attributes which should be saved.

    Yii2 ActiveRecord - save() or Yii2 ActiveRecord - updateCounters() (which is better)