【问题标题】:Laravel get most out of the databaseLaravel 充分利用数据库
【发布时间】:2015-06-18 12:56:40
【问题描述】:

我在Laravel 4 有一个跟踪器,我想知道,我怎样才能从我的桌子上获得“最多”。

所以我想要的是拥有最多访客的那一天。

我的表结构如下:

所以,我的控制器看起来像这样:

public function index()
    {    
        $begin = date('Y-m-01');
        $end = date('Y-m-t');

        $visits = Tracker::selectRaw('date, count(ip)')->groupBy('date')->whereRaw("date between '$begin' and '$end'")->get();

        //get total visits per month
        $get_visits = Visitor::whereRaw("date between '$begin' and '$end'")->count();

        // get average visits
        // transform dates to DateTime objects (we need the number of days between $begin and $end)
        $begin = new \DateTime($begin);
        $end = new \DateTime('now');
        $diff = $end->diff($begin); // creates a DateInterval object
        $days = (int)$diff->format('%a'); // %a  -->  days
        $average_visits = $get_visits / $days;


        return View::make('admin.home.index')->with('stats', $visits)
                                             ->with('get_visits', $get_visits)
                                             ->with('average_visits', $average_visits);

    }

我想要的输出:

我们在 2015 年 6 月 18 日的访问者人数最多(542 名访问者)

例如。

谢谢!

【问题讨论】:

    标签: php laravel-4 tracker


    【解决方案1】:

    您可以SELECT日期ORDER BY访问者数量DESCENDINGLIMIT减1。这是基本的mysql。如何在 laravel 中使用,在documentation.

    按顺序排列:

    ->orderBy('visits', 'desc')
    

    限制:

    ->take(1)
    

    我的示例查询基于一个系统,该系统有一个计算访问的列(您的结构没有)。因此,让我来帮助您了解您的结构。

    您希望按日期获取它,因此您基本上 GROUP BY 日期:

    ->groupBy('date')
    

    从该查询中,您想获得属于该日期的行数。所以你使用 COUNT

    ->count()
    

    这一切都基于您对查询的了解。 这一切都取决于查询生成器。

    【讨论】:

    • 是的,我确实统计了每个月的所有访问者...但我想要总体上的最大值,你明白吗?
    • @RobinR 您想要访问最多的日期吗?
    • @RobinR 是的。我的回答为您提供所需的一切。基本上:选择日期和按日期分组的所有记录的计数,按日期分组的所有记录的计数排序 DESC LIMIT 1。
    • 你能给我举个例子吗? (在 RMO Laravel 查询中?)
    • @RobinR 我会的,我回家的时候。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多