10

in InstallSchema

        ->addColumn(
            'created_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            [],
            'Creation Time'
        )
        ->addColumn(
            'updated_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            [],
            'Update Time'
        )          

so how do updated_at, create_at auto add datetime when execute action?

3 Answers 3

26

Answer provided by @Smartie should work, but you can also achieve this on database level like Magento 2 does for customer entity:

    )->addColumn(
        'created_at',
        \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
        null,
        ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
        'Created At'
    )->addColumn(
        'updated_at',
        \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
        null,
        ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
        'Updated At'

This will set following columns:

`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Created At',
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Updated At',
2
  • @xanka please mark answer as accepted if you are happy with that. Commented Sep 21, 2017 at 10:31
  • Unfortunately it doesn't work in 2022 (M 2.4.3)
    – xpoback
    Commented Jan 19, 2022 at 8:24
4

You need add "default" option with value \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT

->addColumn(
    'created_at',
    \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
    null,
    [
        'nullable' => false, 
        'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT
    ],
    'Created At'
)
3

They are done within the models themselves. For example, when the wishlist model is saved the updated_at is updated in the beforeSave function.

app/code/Magento/Wishlist/Model/Wishlist.php around line 252

 /**
 * Set date of last update for wishlist
 *
 * @return $this
 */
public function beforeSave()
{
    parent::beforeSave();
    $this->setUpdatedAt($this->_date->gmtDate());
    return $this;
}

You can also see something similar in the wishlist item model

app/code/Magento/Wishlist/Model/Item.php

...
public function beforeSave()
{
    ...
    // set current date if added at data is not defined
    if (is_null($this->getAddedAt())) {
        $this->setAddedAt($this->_date->gmtDate());
    }
    ...
}
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.