YII migrations and by default values for table columns

10,476

Solution 1

Leverage off the MySQL Create Table Script:

show create table tablename

Which gives:

CREATE TABLE `tablename` (
....
....
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
...

Now Add that to the migration:

'timestamp' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP'

Solution 2

For google users like me: Yii2 now has it out of the box.

Now you can add ->defaultExpression('CURRENT_TIMESTAMP') to your definition.

Share:
10,476
Factory Girl
Author by

Factory Girl

Updated on June 04, 2022

Comments

  • Factory Girl
    Factory Girl almost 2 years
    public function up(){
    
            $this->createTable('POST', array(
                'id' => 'pk',
                'isremoved' => 'integer NOT NULL',
                'removaldate' => 'timestamp NULL',
                'post' => 'text NOT NULL',
                'creationdate' => 'timestamp NOT NULL',
            ));
    }
    

    This is the up function for migration. As u see it is query for creating new table. By default YII creates default value for timestamp column equal to CURRENT_TIMESTAMP and crates additional parameter and sets it equal to ON UPDATE CURRENT_TIMESTAMP.

    I do not need current value for timestamp and i do not need to update this column on updating row. What i must to do? By the way, u use MySQL