douyinbo3361 2017-05-02 22:22
浏览 113
已采纳

Laravel在给定的时间间隔内获取数据库中的条目

I want to display in the admin panel statitics about users and other things in the database. For example to show how many users were registered today, this month etc. For now I am doing this with the users for today the following way:

$users = User::where('admin', 0)->get();

    $usersRegisteredToday = array_filter($users->toArray(), function ($user) {
        $registerDate = \DateTime::createFromFormat('Y-m-d H:i:s', $user['created_at']);
        $registerDate->setTime(0,0,0);
        $today = new \DateTime();
        $today->setTime(0,0,0);

        $diff = $today->diff($registerDate);
        $diffDays = (integer)$diff->format("%R%a"); // Extract days count in interval
        return  $diffDays == 0;
    });

    return view('admin.index', compact("users", "usersRegisteredToday")); 

And in the view:

<p class="text-no">Today: {{ count($usersRegisteredToday) }} </p>

I wonder if there is a better, simpler and faster way to do this, because I think if I get the information for the other things that way it will be very slow and heavy. So i want to know the best and lightest way to do this.

  • 写回答

3条回答 默认 最新

  • duanaidang6197 2017-05-02 22:54
    关注

    As of Laravel 5.3 we can use whereDate / whereMonth / whereDay / whereYear

    For example to get records created today:

    $users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();

    Possibly a similar question is asked here: Get only records created today in laravel

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作