2016-10-28 39 views
0

我試圖讓從我的銷售表吐出這樣的查詢:Laravel雄辯:多選和where子句查詢

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 
    } 

我有這個,但它不是吐出任何東西。如果我刪除wheres它會得到這些款項不在我需要的日期範圍內,所以我知道它的問題。我不確定是否可以做多個小麥

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'); 

    } 
+0

select必須像' - > select([])''。選擇列表必須在列 – Faradox

+0

如果我刪除了'where'選項並且addSelect工作正常 – Packy

+0

在「選擇」之後移動所有的列表。 – Faradox

回答

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;