How to Create Auto Update Time Attributes in InstallSchema of Magento 2
This topic is written with the purpose to help you create auto-update time attributes in InstallSchema of Magento 2 by using MYSQL.
How to create auto update time attributes in InstallSchema of Magento 2
MYSQL will work directly with TIMESTAMP and DATETIME, that are allowed to automatically initialize, update and show the current date and time on your website instead of you must insert manually the proper value of the date and time into your PHP code, specifically as:
-
Auto-initializing time attributes means auto-loading the current timestamp and datetime.
-
Auto-updating time attributes means auto-renewing to the current timestamp and datetime.
To build auto-update time attributes perfectly in Magento 2 store, you can refer the following script code. The code needs to be added into InstallSchema file.
app/code/Mageplaza/HelloWorld/Setup/InstallSchema.php
Here there are two columns created_at
and update_at
included in your table. When you set a new row to the data table, auto-initializing will be done in the created_at column and the updated_at will be changed if you continue to update a row in the data table.
...
->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'
)
->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'
)
...
Finally, you need to run the command php bin/magento setup:upgrade
in console, after that, the created_at
and updated_at
fields will be established in MYSQL.
When you complete all, that means you can use the auto-updating time attributes in InstallSchema
in Magento 2.
Conclusion
That’s how to create auto update time attributes in Magento 2 InstallSchema. Remember to double-check if there is something wrong.
I hope this is a helpful tutorial. If you have any question or want to discuss more about this topic, feel free to let me know.
Thanks for reading!
Related Topics
- How to create a simple Hello World module for Magento 2
- Magento 2 Block Template Ultimate Guides
- How to Create Module in Magento 2
- How to Create Controller in Magento 2
- How to create CRUD Models in Magento 2
- How to Create Magento 2 Block, Layout and Templates
- Configuration - System.xml
- How To Create Admin Menu In Magento 2
- Admin ACL
- Admin Grid
People also searched for
- magento 2 create autoupdate time attributes in installschema
- 2.3.x, 2.4.x