【问题标题】:Laravel Carbon::today() method return previous dayLaravel Carbon::today() 方法返回前一天
【发布时间】:2020-10-27 16:32:57
【问题描述】:

我编写了一个函数来根据日期过滤用户和代理预订的票。这基本上是一个订票应用程序。在这个用户和代理可以预订不同的票,所以在管理仪表板中,我显示了用户今天预订的票总数,反之亦然。因此,我使用 Carbon 来验证今天的日期。但我得到了不同类型的输出!

控制器:

$ticketsTodayUsers = Booking::with('users')->where("createdAt", ">=", Carbon::today())->whereHas("users", function($subQuery){ 
    $subQuery->where("usertype", "=", "normal");
    })->get();

因此,在此我有两个表,booking 和 user 表,我通过它们验证今天使用 carbon::today() 创建的票证,用户类型为普通或代理。

但是当我今天(2018 年 9 月 19 日)检查时,我得到了昨天(2018 年 9 月 18 日)的计数结果。我没有得到今天的计数,它是零,而是计数来自昨天或很久以前,如 2018 年 9 月 14 日。我不知道我在哪里做错了!

主要条件是我需要将每天的用户和代理预订计数分开,因此通过使用从 db 和 carbon today 函数提交的 createdAt 文件,我试图匹配两者。但我没有得到预期的答案!

【问题讨论】:

  • 需要检查的几件事:你的数据库的时区,你的 PHP 的时区,你的 Laravel 应用程序的时区——这三个都可以不同。然后,删除->get() 并执行dd($ticketsTodayUsers->toSql(), $ticketsTodayUsers->getBindings()) 以输出查询和传递给它的参数。找出为什么该查询没有输出您期望的结果。
  • 当我给 getBindings() 时,我得到 date: 2018-09-19 00:00:00.0 UTC (+00:00) 结果,当我给 tosql "select * from bookings where createdAt >= ? 并且存在(选择 * from users where bookings.userid = users.userid and usertype = ?)"

标签: php laravel laravel-5 php-carbon


【解决方案1】:

尝试使用 $tz 参数 - TimeZone。

Carbon::today('Asia/Calcutta');

并尝试使用WhereData()WhereDay()

->whereDay('createdAt', '=', date('d'))

->whereDate('createdAt', Carbon::today())

当然有适当的时区

Booking::with('users')->whereDate('createdAt', Carbon::today('Asia/Calcutta')->toDateString())->whereHas("users", function($subQuery){
            $subQuery->where("usertype", "=", "normal");
        })->get();

【讨论】:

  • 知道印度的时区吗?
  • '亚洲/加尔各答',
  • 不,我仍然遇到同样的问题!
  • 更新了答案
【解决方案2】:

试试这个:

$ticketsTodayUsers = Booking::with('users')
     ->whereDate("createdAt", ">=", Carbon::now()->toDateString())
     ->whereHas("users", function($subQuery){ 
         $subQuery->where("usertype", "=", "normal");
     })->get();

【讨论】:

    【解决方案3】:

    这对我有帮助

    $ticketsTodayUsers = Booking::with('users')->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->addHour()])->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-28
      • 2019-02-07
      • 2020-09-17
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2020-10-26
      相关资源
      最近更新 更多