9

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?

23

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',
| improve this answer | |
  • @xanka please mark answer as accepted if you are happy with that. – Wojtek Naruniec Sep 21 '17 at 10:31
3

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'
)
| improve this answer | |
2

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());
    }
    ...
}
...
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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