Laravel Eloquent:多个select和where子句查询

时间:2016-10-28 18:03:57

标签: php mysql laravel

我正在尝试从我的销售表中获取一个查询:

For each `Brand`    
   `Brand` {
      this month `sum(quantity)`
      this month last year `sum(quantity)`
      this year `sum(quantity)`
      this last year `sum(quantity)`
      `Brand` name
    }
    Next `Brand` {
      this month `sum(quantity)`
      this month last year `sum(quantity)`
      this year `sum(quantity)`
      this last year `sum(quantity)`
      `Brand` name
    }

我有这个,但它没有吐出任何东西。如果我删除了这些数据,它将得到的数额不在我需要的日期范围内,所以我知道它的问题。我不确定我能不能做多次

public function sales()
    {

        return $this->hasMany('App\Sale', 'account_vip_id', 'vip_id')
                                     ->select('brand', DB::raw('sum(quantity) as month'))->whereMonth('date','=',date('m'))
                                     ->addSelect('brand', DB::raw('sum(quantity) as month_last'))->whereDate('date','=',date('m Y',strtotime("-1 year")))
                                     ->addSelect('brand', DB::raw('sum(quantity) as year'))->whereYear('date','=',date('Y'))
                                     ->addSelect('brand', DB::raw('sum(quantity) as year_last'))->whereYear('date','=', date("Y",strtotime("-1 year")))
                                     ->groupBy('brand');

    }

1 个答案:

答案 0 :(得分:0)

不幸的是,SQL并不像这样工作。您需要将where子句放在sum函数中。我创建了一个快速查询,让您更好地了解我所谈论的内容......

SELECT 
    brands.name,
    SUM( IF( DATE_FORMAT(NOW(), '%y-%m') = DATE_FORMAT(sales.created_at, '%y-%m'), sales.quantity, 0) ) AS `month`,
    SUM( IF( DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%y-%m') = DATE_FORMAT(sales.created_at, '%y-%m'), sales.quantity, 0) ) AS `last_month`,
    SUM( IF( YEAR(CURDATE()) = YEAR(sales.created_at), sales.quantity, 0) ) AS `year`,
    SUM( IF( YEAR(CURDATE()) - 1 = YEAR(sales.created_at), sales.quantity, 0) ) AS `last_year`
FROM brands
INNER JOIN sales ON brands.id = sales.brand_id
GROUP BY brands.name;