Yii Framework - Automatically timestamps create and update operations

alfa6661
- May 15, 2015
0 (0 votes)
Rate :
How to automatically populates / updates created_at and updated_at column when you create or update a model instance.

This article will show you how to automatically populates / updates created_at and updated_at column when you create or update a model instance. We will set the two date/time column values on different task. so we need to use scenario as the useful tool for separating tasks on your model.

Syntax

# protected/models/YourModel.php
public function rules() {
	....
	array('created_at', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'insert'),
	array('updated_at', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'update'),
}

with above code, created_at and updated_at column will managed by Active Record. ActiveRecord automatically populates / updates them when you create or update a model instance.

  1. created_at - Automatically set to the current date and time when the record is first created.
  2. updated_at - Automatically set to the current date and time whenever the record is updated.

Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter

– Eric S. Raymond

Have a better explanation?

If you have comments about this post. Please write your comments below

No comments associated with this article