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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程