2017-06-06 10 views
0

私はすべてが働いているカスタムYii2 TimestampBehavior

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

私のモデルで動作しています。しかし、私は1つのアクションでのみ動作しないことが必要です。 actionViewでは "update_at"属性が変更されていないことが必要です。私の行動ビュー:

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

できるだけ正確にこれを行うことができますか?

答えて

2

使用:検証が実行する必要がある場合

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

最初のパラメータは決定は(この例では、それは必要はありません)、第二保存しなければならない属性を決定します。

Yii2 ActiveRecord - save()またはYii2 ActiveRecord - updateCounters()(優れている)

+0

dbでは "updated_at"は変更されません。しかし、ビュー(レンダリング)ではまだ属性 "update_at"を変更しています。 – Vitaxxxa

+0

保存後 '$ model-> refresh()' – Yupik

+0

はい、その仕事、tnx – Vitaxxxa

0

あなただけの特別なメソッドActiveRecord::updateCounters()でそれを更新することができます。

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