douyinbo3361 2017-05-02 14: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 14: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 STM32悬赏求解答,ai不要来解答
  • ¥15 Mysql 一张表同时多人查询和插入怎么防止死锁
  • ¥20 centos6.7 安装libevent库.总是报错,如何解决?
  • ¥15 电脑买回,学校的有线网络总掉。
  • ¥20 关于普洛菲斯触摸屏与AB连接地址问题
  • ¥15 syri可视化不显示插入缺失
  • ¥30 运行软件卡死查看系统日志分析不出来
  • ¥15 C语言代码改正特征选择算法设计,贝叶斯决策,,设计分类器,远程操作代码修正一下
  • ¥15 String 类valuve指向的问题
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部