没有不值得去解决的问题,也没有不值得去学习的技术!

SQLSTATE[42000]: 1067 Error When Setting Default datetime to ‘0000-00-00 00:00:00’ in Laravel 9 and MySQL 8.0

In MySQL 8.0, setting the default value of a datetime field to '0000-00-00 00:00:00' throws the error: SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'operated_at_gmt'

1. In MySQL 8.0, setting the default value of a datetime field to ‘0000-00-00 00:00:00’ throws the error: SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for ‘operated_at_gmt’. See Figure 1.

In MySQL 8.0, setting the default value of a datetime field to '0000-00-00 00:00:00' throws the error: SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'operated_at_gmt'
Figure 1

2. Reference: https://www.shuijingwanwq.com/2022/09/28/6993/ In Navicat for MySQL, when copying a table from one database to another, an error occurs: [ERR] 1292 – Incorrect datetime value: ‘0000-00-00 00:00:00’ for column ‘created_at_gmt’ at row 1 (in MySQL 8.0).

3. Now I need to set the SQL mode permanently. Reference: https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html 5.1.11 Server SQL Modes

4. Edit C:\ProgramData\MySQL\MySQL Server 8.0\my.ini, search for: sql-mode, and remove: NO_ZERO_IN_DATE,NO_ZERO_DATE, keeping the rest.

Plaintext

# sql-mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
sql-mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

5. After restarting the computer, re-running the corresponding SQL still throws an error. However, manually changing the datetime value of a record to ‘0000-00-00 00:00:00’ in the database succeeds. See Figure 2.

After restarting the computer, re-running the corresponding SQL still throws an error. However, manually changing the datetime value of a record to '0000-00-00 00:00:00' in the database succeeds.
Figure 2

6. I copied the failing SQL and executed it manually in the database, which succeeded. See Figure 3.

Copied the failing SQL and executed it manually in the database successfully
Figure 3

7. Reference: https://stackoverflow.com/questions/18067614/how-can-i-set-the-default-value-of-a-timestamp-column-to-the-current-timestamp-w . I adjusted the migration file and gave up setting the default value to ‘0000-00-00 00:00:00’. See Figure 4.

Adjusted the migration file and gave up setting the default value to '0000-00-00 00:00:00'
Figure 4
PHP
// $table->dateTime('operated_at_gmt')->default('0000-00-00 00:00:00')->comment('操作时间')->index();
$table->dateTime('operated_at_gmt')->comment('操作时间')->index();

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系