douwen3965 2017-03-14 04:28 采纳率: 0%
浏览 137
已采纳

查询created_at时忽略秒

I have a scheduled task that runs every 5 minutes that collects some stats on a server I run.

There is a small delay whilst it waits for the request to come back and so records are always being saved 2 or 3 seconds later. I.e the task runs at 2017-14-03 08:00:00, but the records are saved at 2017-14-03 08:00:03.

I am trying to pull the records out to display on a graph. The graph scales to the time period you want to look at (through hard coded buttons that refresh the graph with new data).

The first graph I am trying to do is one over the last 24 hours. Rather than bring back every 5 minute point for the last 24 hours, I just want one per hour. I have built a function to round down to the nearest hour and then get the last 24 hours based off that - it looks like this:

public function last24Hours()
{
    $times = [];
    $time = Carbon::now()->minute(0)->second(0);
    $i = 1;
    while($i <= 24)
    {
        array_push($times, $time->toDateTimeString());
        $time->subHour();
        $i++;
    }

    return $times;
}

Using the times returned, I am trying to query the model with whereIn() like so:

$stats = ServerTracking::whereIn('created_at', $this->last24Hours())->get();

The query runs, but nothing comes back - as the created_at time is a couple of seconds off from what I am querying.

I've hit a bit of a roadblock and cannot think of a way to get around this? Any ideas?

  • 写回答

2条回答 默认 最新

  • douzhaochan6468 2017-03-14 04:52
    关注

    You can use selectRaw with a formatted date:

    $stats = ServerTracking::selectRaw('foo,bar,DATE_FORMAT(created_at, "%Y-%m-%d %H:00:00") as hour_created')->get()->keyBy('hour_created');
    

    All of the values in each hour will have the same hour_created, and keyBy will only keep one of them (from docs):

    If multiple items have the same key, only the last one will appear in the new collection.

    Just replace foo and bar with the other values you need. You'll either keep the 0:55 minute values, or the 0:00 minute values, depending on how you sort the query.

    Come to think of it, you could use whereRaw to do it your way:

    ->whereRaw("DATE_FORMAT(created_at, '%Y-%m-%d %H:00:00') in (" .implode(",",$last24Hours). ")")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看