Automating timestamps
For instance, we have a simple blog application. As in any blog, it has posts, comments, and so on. We would like to populate the timestamps during the create/update events for posts. Let us assume that our post model is named BlogPost
model.
Getting ready
Create a new application using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
Set up the database connection and create a table named
blog_post
, as follows:DROP TABLE IF EXISTS 'blog_post'; CREATE TABLE IF NOT EXISTS 'blog_post' ( 'id' INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 'title' VARCHAR(255) NOT NULL, 'text' TEXT NOT NULL, 'created_date' INTEGER, 'modified_date'INTEGER, PRIMARY KEY ('id') );
Use Gii to create a model for the
blog_post
table.
How to do it...
Add the following method to
models/BlogPost.php
:/** * @return array */ public function behaviors() { return [ 'timestamp'=> [ ...