简体   繁体   English

0000-00-00 作为 Laravel 中的日期

[英]0000-00-00 as date in Laravel

I have to build a Laravel application on an existing (old) database.我必须在现有(旧)数据库上构建 Laravel 应用程序。 This database uses 0000-00-00 as default dates.该数据库使用 0000-00-00 作为默认日期。 There is no way I can change this because the current system (which will also be kept) uses this to check if something is active for an infinite amount of time (for example: active_from 0000-00-00 & active_till 0000-00-00 means it's always active).我无法改变这一点,因为当前系统(也将保留)使用它来检查某些东西是否在无限时间内处于活动状态(例如: active_from 0000-00-00 & active_till 0000-00-00意味着它始终处于活动状态)。

I want to add a column to an existing table, so I created a migration: add_columnname_to_tablename_table .我想向现有表中添加一列,因此我创建了一个迁移: add_columnname_to_tablename_table In the up() function I did: $table->string('columnname') .up()函数中,我做了: $table->string('columnname') When I run the migration, I get:当我运行迁移时,我得到:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '0000-00-00 00:00:00' for column active_from at row 1. SQLSTATE[22007]:无效的日期时间格式:1292 不正确的日期时间值:'0000-00-00 00:00:00' 列active_from在第 1 行。

The old system is too big to make any changes to this -- and I'm not allowed to change it.旧系统太大而无法对此进行任何更改 - 我不允许更改它。

Is there any way to make Laravel accept 0000-00-00 as a valid date(time)?有没有办法让 Laravel 接受 0000-00-00 作为有效日期(时间)?

Laravel默认使用严格模式,我通过改变固定此strict => trueconfig/database.phpstrict => false

This is mostly a MySql issue, as zero dates are disabled for newer versions of MySql.这主要是一个 MySql 问题,因为较新版本的 MySql 禁用了零日期。 In addition, the NO_ZERO_DATE mode was deprecated (see: https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_no_zero_date ).此外,不推荐使用NO_ZERO_DATE模式(请参阅: https : NO_ZERO_DATE )。 To get around this, you could change all zero dates in your database to the unix epoch time 1970-01-01 00:00:00 (which is what I had to do with mine after upgrading MySql).为了解决这个问题,您可以将数据库中的所有零日期更改为 unix 纪元时间1970-01-01 00:00:00 (这是我升级 MySql 后必须处理的)。

strtotime will return a number below zero when the date is invalid such as common in MySQL 0000-00-00 00:00:00.当日期无效时,strtotime 将返回一个低于零的数字,例如 MySQL 中常见的 0000-00-00 00:00:00。 Make sure you pass an object type date or carbon:确保传递对象类型日期或碳:

  return strtotime(date or carbon object) < 0 ? null : date

I found out that you need to first set the SQL column type to TIMESTAMP and then when storing data use date() inbuilt php function我发现您需要先将 SQL 列类型设置为TIMESTAMP ,然后在存储数据时使用 date() 内置的 php 函数

$myModel->my_date = date('y-m-d');

it will save in proper format just like created_at and updated_at .它将以正确的格式保存,就像created_atupdated_at

Example data when saved:保存时的示例数据:

"start_date": "2021-08-14 00:00:00",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM