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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler