dongtuwu8548 2015-06-18 12:56
浏览 81
已采纳

Laravel充分利用了数据库

I'm having a tracker in Laravel 4 and I was wondering, how can I get the 'most' from my table.

So want I want is to have the day that had the most visitors.

My table structure looks like this:

Structure

So, my controller looks like this:

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);

    }

What I want as an output:

We had the most visitors on 18/06/2015 (542 visitors)

For example.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongmiyi8220 2015-06-18 13:10
    关注

    You can SELECT the date ORDER BY the amount of visitors DESCENDING and LIMIT by 1. This is basic mysql. How to use this in laravel, is in the documentation.

    Order by desc:

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

    Limit:

    ->take(1)
    

    My example query is based on a system that has a column which counts the visits(which your structure doesn't have). So let me help you with your structure.

    You want to have it by date so you basically GROUP BY date:

    ->groupBy('date')
    

    From this query you want to have the amount of rows that belong to that date. So you use COUNT:

    ->count()
    

    This is all based on that you know stuff about queries. This is all according to the query builder.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看