Magento 2 CRUD Models: Create and Update Time – How to Guide

magento2ormPHP

I've created a Magento 2 CRUD/Abstract model that updates the following MySQL table.

CREATE TABLE `pulsestorm_commercebug_log` (
  `pulsestorm_commercebug_log_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Entity ID',
  `json_log` mediumtext NOT NULL COMMENT 'Demo Title',
  `creation_time` timestamp NULL DEFAULT NULL COMMENT 'Creation Time',
  `update_time` timestamp NULL DEFAULT NULL COMMENT 'Modification Time',
  `is_active` smallint(6) NOT NULL DEFAULT '1' COMMENT 'Is Active',
  PRIMARY KEY (`pulsestorm_commercebug_log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='pulsestorm_commercebug_log';

I can successfully use the model's save method to add data to this table. However, the creation_time and update_time columns are not updated. Their initial values are NULL.

Do I need to do something special with my models to get these creation and update times columns working? Does anyone that's run into similar problems know of a solution?

If not — does anyone know where in Magento 2's code base the ORM normally populate these values? (so I can debug what's wrong with my Models there)

Best Answer

It turns out (thanks KAndy!) that the creation and update timestamps are not handled on the ORM level. If you want this functionality, you need to make sure your database tables are created with the correct timestamp attributes. i.e., in your install schema, something like.

    )->addColumn(
        'creation_time',
        \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
        null,
        ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
        'Creation Time'
    )->addColumn(
        'update_time',
        \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
        null,
        ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
        'Modification Time'
    )