Laravel - 从开始

时间:2016-06-01 08:12:33

标签: php mysql laravel eloquent

我在Laravel 5.2中根据用户选择的时间长度进行查询,其中一个选项自开始以来,用于查看,评论等数量。我正在使用ajax发送fromto个日期。 我想知道我应该发送什么样的日期格式才能从DB中获取所有行?

在这一行中,我创建了选定时期的日期范围:

$period = new DatePeriod( new DateTime($from), new DateInterval('P1D'), new DateTime($to));

然后我向他们添加0值。在查询之后,如果它们存在,我将使用DB中的值替换0。

这是我的控制者:

    public function timelines(Request $request){
    $from = $request['from'];
    $to = $request['to'];

    //if option time, get the date for number of views for each hour of the day
    if ($request['option'] == 'time'){
      $data = View::groupBy('time');
      $data->orderBy('time', 'ASC');

      if ($from !=0 && $to != 0)
         $data->whereBetween('views.created_at', [$from.' 00:00:00', $to.' 00:00:00']);

      $data->get([
           DB::raw('Hour(created_at) as time'),
           DB::raw('COUNT(*) as "count"')
           ]);

      foreach($data as $val){
       $dbData[$val->time] = $val->count;
      }

      $data = array_replace(array_fill_keys(range(0, 24), 0), $dbData);
    }

    //based on option selected, get data for number of articles read, number of comments, number of "bli med"
    else {

      $data = DB::table($request['option']);
      $data->select(DB::raw('DATE(created_at) as time'), DB::raw('count(*) as count'));

      if ($from !=0 && $to != 0) {
        //create an array with dates for the time interval specified
        $period = new DatePeriod( new DateTime($from), new DateInterval('P1D'), new DateTime($to));
        $dbData = [];

        //create an array with dates set as keys, and value 0
        foreach($period as $date){
            $range[$date->format("Y-m-d")] = 0;
        }
        $data->whereBetween('views.created_at', [$from.' 00:00:00', $to.' 00:00:00']);
      }

      $data->groupBy('time');
      $data->get();

      //create an array with dates set as keys, and value as count from DB
      foreach($data as $val){
        $dbData[$val->time] = $val->count;
      }

      //replace the values in two arrays
      $data = array_replace($range, $dbData);
    }

    return json_encode($data);
  }

当我得到它时,我得到了:

  

尝试获取非对象的属性

这段代码:

foreach($data as $val){
    $dbData[$val->time] = $val->count;
}

因为我从查询中返回了构建器。 如何创建一个查询,我可以从表中获取所有结果,并创建自该表开始以来的日期范围的日期帐户。

0 个答案:

没有答案