如何在InstallSchema magento2中自动添加日期时间?


9

在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'
        )          

那么怎么办updated_atcreate_at自动添加日期时间时执行的行动?

Answers:


23

@Smartie提供的答案应该可以,但是您也可以像Magento 2那样在数据库级别为客户实体实现此目的:

    )->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'

这将设置以下列:

`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',

如果您对此满意,请@xanka将答案标记为已接受。
Wojtek Naruniec

3

您需要添加带有值\ 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'
)

2

它们是在模型本身内完成的。例如,当保存心愿单模型时,在beforeSave函数中更新了updated_at。

第252行附近的app / code / Magento / Wishlist / Model / Wishlist.php

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

您还可以在愿望清单项目模型中看到类似的内容

应用程序/代码/ Magento /愿望清单/模型/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());
    }
    ...
}
...
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.