Laravel where子句在foreach循环中不断增加

时间:2018-08-15 07:59:03

标签: php database laravel eloquent

我有一个销售表,存储着每天的每笔销售记录,分别为user_id,数量,收入,sales_date。现在,我想从此销售表中获取每月销售报告,

 $months = [1,2,3,4,5,6,7,8,9,10,11,12];
       $sales = ArtistSale::query()->where('artist_id', $artist->id)
           ->whereYear('sales_date', $year);
           if($sales->exists()){
                foreach ($months as $month) {
                   $month_sales->put($month, $sale>whereMonth('sales_date',$month)>toSql());
                }
                return $month_sales;
            }
            return 'no sales for the year'
       
     this is the query to get monthly reports 

这导致whereMonth子句每月重复enter image description here

2 个答案:

答案 0 :(得分:1)

如果您确实需要每个月进行一次查询,则需要创建一个新的查询对象:

$months = [1,2,3,4,5,6,7,8,9,10,11,12];
$sales = ArtistSale::query()->where('artist_id', $artist->id)
       ->whereYear('sales_date', $year);
if($sales->exists()){
      foreach ($months as $month) {
          $newQuery = clone $sales;
          $month_sales->put($month, $newQuery->whereMonth('sales_date',$month)->toSql());
       }
       return $month_sales;
}
return 'no sales for the year'

但是,您可以通过对所有内容进行组合选择来避免所有这些情况:

$months = [1,2,3,4,5,6,7,8,9,10,11,12];
$sales = ArtistSale::query()->where('artist_id', $artist->id)
       ->whereYear('sales_date', $year)
       ->where(function ($query) use ($months) {
            foreach ($months as $month) {
                //Since months has all months this is not really needed but would be needed if you decided to remove a few months from the above array
                $query->whereMonth('sales_date', '=', $months, "or");
            }
        })->get();
 if ($sales && $sales->isNotEmpty()) {
    return $sales->groupBy(function ($sale) {
       //This assumes that you have sales date in your $dates cast fields
       return $sale->sales_date->format('M'); 
    });
 } else {
     return 'no sales for the year';
 }

这将执行单个查询并返回按月分组的结果。

答案 1 :(得分:0)

您应该使用现有销售中的where扩展查询,然后调用get获得结果。这样,您应该只有2个查询。一个用于检查是否存在,第二个用于检查所需数据。

注意: 代码未经测试,请更正代码中不正确的部分。

 $months = [1,2,3,4,5,6,7,8,9,10,11,12];
 $sales = ArtistSale::where('artist_id', $artist->id)->whereYear('sales_date', $year);
 if($sales->exists()){
     foreach ($months as $month) {
         $sales->whereMonth('sales_date', $month);
     }
     return $month_sales->get();
  }
  return 'no sales for the year'