根据过滤器参数,按时间过滤多种方法

时间:2018-01-14 13:29:34

标签: database laravel eloquent

我确实有三种方法可以在我的管理信息中心上返回一些数据。他们工作正常。但是,客户希望按时间进行一些过滤。

所以我确实有一些参数从vuejs发送到后端,如:

filterByPeriod: {

   from:YYYY-MM-DD,
   to:  YYYY-MM-DD

}

我可以通过请求类获取这些参数,我的问题是如何根据时间过滤这些方法

private function getReservationSources()
{
        return Reservations::where('user_id', request('user_id')
            ->leftJoin('tracking_codes', 'form_submissions.tracking_code_id', '=', 'tracking_codes.id')
            ->leftJoin('tracking_sources', 'tracking_sources.id', '=', 'tracking_codes.tracking_source_id')
            ->select(DB::raw("count(form_submissions.id) as value, tracking_sources.name as name"))
            ->groupBy('tracking_sources.name')
            ->orderBy('value', 'desc')
            ->get();

}

private function getReservationTrackingCodes()
{

        return Reservations::where('user_id', request('user_id')
            ->leftJoin('tracking_codes', 'form_submissions.tracking_code_id', 'tracking_codes.id')
            ->select(DB::raw('count(tracking_codes.id) as value, tracking_codes.label as name'))
            ->groupBy('tracking_codes.label')
            ->orderBy('value', 'desc')
            ->take(10)
            ->get();

}

private function getReservationReferrers()
{

    return Reservations::where('user_id', request('user_id')
        ->select(DB::raw("count(form_submissions.id) as value, form_submissions.referrer as name"))
        ->groupBy('form_submissions.referrer')
        ->orderBy('value', 'desc')
        ->take(10)
        ->get();
}

2 个答案:

答案 0 :(得分:0)

使用whereBetween()方法:

->whereBetween('created_at', [Carbon::parse($request->from), Carbon::parse($request->to)])

答案 1 :(得分:0)

正如我所看到的所有方法都来自同一个模型,所以你可以用另一种方法来拉动模型:

private function getReseravtions(){

 $builder = Reservations::where('user_id', request('user_id');

 return $this->filterByPeriod($builder);

}

首先,您只需构建一个雄辩的构建器而不执行查询,并通过另一个过滤方法发送它:

 private function filterByPeriod(Builder $builder)
 {
  if(empty(request('filterByPeriod')){

      return $builder;
  }

  $period = json_decode(request('filterByPeriod'));

  if($period->from)
  {

     $builder->where('reservations.created_at', '>=', Carbon::parse($period->from)->startOfDay());
  }

  if ($period->to) 
  {

    $builder->where("reservations.created_at", "<=", Carbon::parse($period->to)->endOfDay());
  }

  return $builder;
}

然后只需在方法中调用这样的保留

private function getReservationReferrers()
{

        return $this->getReservations()
            ->select(DB::raw("count(form_submissions.id) as value, form_submissions.referrer as name"))
            ->groupBy('form_submissions.referrer')
            ->orderBy('value', 'desc')
            ->take(10)
            ->get();
 }

如果您应用了一些过滤,它将根据dat的开始和一天结束碳实例进行过滤。如果没有,那么它只会返回未经过滤的构建器并继续运行。

由于我正在注入构建器,请记住构建器是一个雄辩的构建器而不是查询构建器实例,因此在顶部使用它

use Illuminate\Database\Eloquent\Builder;