自定义 Yii2 时间戳行为

Custom Yii2 TimestampBehavior

我的模型有行为

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

一切正常。但我只需要一个动作是行不通的。 有必要在 actionView 中没有更改 "update_at" 属性。我的动作视图:

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

我怎样才能尽可能正确地做到这一点?

使用:

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

第一个参数确定是否应该进行验证运行(对于本例来说不需要),第二个参数确定应保存的属性。

Yii2 ActiveRecord - save() or Yii2 ActiveRecord - updateCounters()(哪个更好)

您可以使用特殊方法更新它 ActiveRecord::updateCounters()

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