![](/img/trans.png)
[英]Laravel5 Eloquent select from multiple table with where clause
[英]Laravel Eloquent : multiple select and where clause query
我試圖獲取一個查詢,該查詢從我的銷售表中吐出:
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');
}
不幸的是,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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.