gpt4 book ai didi

mysql - 使用 Laravel 和 MySQL 比较时间

转载 作者:行者123 更新时间:2023-11-29 11:02:08 25 4
gpt4 key购买 nike

在 Laravel 应用程序中,我的 MySQL 数据库中有一些类型为 time (不是 datetime)的列。我使用 Carbon 在我的模型中转换这些时间列,如下所示:

public function getStartDateAttribute()
{
return Carbon::createFromFormat('H:i:s', $this->attributes['start_time]);
}

问题在于 Carbon 会自动将任何未指定的字段(例如月、日、年)设置为当前日期。

这会在比较时间时产生问题。

例如,假设我们有一个名为 Foo 的模型,有 2 条记录:

  • id:10start_time5:00am
  • id:30start_time3:00am

以及以下代码:

 // Date and time the code was executed is 25/11/2016
$a = Foo::first('id', 10)->start_date; // Fetched at 11:59pm
// ... some delay ...
$b = Foo::first('id', 30)->start_date; // Fetched at 00:00am (date is now 26/11/2016)
dump($a->gte($b)); // where $a and $b are carbon objects

通常最后一条语句几乎总是返回 true,因为凌晨 5:00 晚于凌晨 3:00。

但是,由于 $a 是在晚上 11:59 获取的,而 $b 是在上午 00:00 获取的,因此无论 'start_date' 的值是多少,该语句将始终返回 false!

据我所知,这是一个罕见的极端情况,但这就是黑客攻击的方式。

因此我的问题是,处理和比较MySQL时间列的时间的正确方法是什么?

最佳答案

您可以使用 php strtotime功能如下:

在您的模型中:

public function getStartTimeAttribute($value)
{
return strtotime($value);
}

然后在你的 Controller 中:

$a = Foo::first('id', 10)->start_time; // Fetched at 11:59pm
$b = Foo::first('id', 30)->start_time; // Fetched at 00:00am
dump($a <= $b); // evaluates to false

关于mysql - 使用 Laravel 和 MySQL 比较时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42052235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com