0

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?

Vitaxxxa
  • 29
  • 5

2 Answers2

3

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)

Yupik
  • 4,932
  • 1
  • 12
  • 26
1

You may just update it with special method ActiveRecord::updateCounters().

$model = $this->findModel($id);
// Don't forget to check whether the model is null
if ($model !== null) {
    $model->updateCounters(['views' => 1]);
}
SiZE
  • 2,217
  • 1
  • 13
  • 24