【问题标题】:Laravel 8 query builder filter results by two datetime columns with whereDateLaravel 8 查询生成器通过两个带有 whereDate 的日期时间列过滤结果
【发布时间】:2021-04-18 07:58:30
【问题描述】:

我正在使用 Laravel 8 的查询构建器从我的数据库中返回一个特定的结果。我的查询已经部分处理了我需要的大部分内容,但是在尝试基于两个特定的 datetime 列进行过滤时遇到了一些问题。

我有两列:period_fromperiod_to,我希望能够在period_from 列的给定日期之后返回相关结果,但之前period_to 列的日期不同,这是我目前所得到的:

$events = GoogleAnalytics::where('event_category', $category)
                        ->where('event_action', $action)
                        ->whereDate('period_from', $dateFrom)
                        ->whereDate('period_to', $dateTo)
                        ->orderBy('created_at', 'desc')
                        ->first();

不幸的是,这不起作用,如果我删除period_to 列,我可以获得结果,但我需要在两个日期之间进行过滤。为什么这不起作用?请给我一些指导吗? :)

【问题讨论】:

  • 我觉得你需要一些东西whereBetween('period_from ', [$dateFrom, $dateTo])
  • 使用where。如->where('period_from', '>=', $dateFrom)->where('period_to', '<=', $dateTo)
  • 以上建议都不适合我。 whereBetween 不返回任何结果,使用 where 的组合只返回一天的结果。我基本上需要从给定日期获取period_from 之后的所有内容,直到period_to 但在period_from 之后的所有内容
  • 您的查询中有 first() ,也许这就是单日的原因?更改为 get() 并检查
  • 我有->first() 因为我只需要返回结果中的最新结果

标签: php mysql laravel laravel-8


【解决方案1】:

尝试将运算符与 where 查询一起添加。

$events = GoogleAnalytics::where('event_category', $category)
                    ->where('event_action', $action)
                    ->where('period_from', '<', $dateFrom)
                    ->where('period_to', '>', $dateTo)
                    ->orderBy('created_at', 'desc')
                    ->first();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多