2016-01-31 103 views
1

我有3個表。用戶,帳戶和預訂。我已經嘗試了三次表連接和年月明智的查詢。 [3 Table diagram] [1]Laravel加入表並查詢

但查詢預約計算顯示錯誤。它顯示了兩倍的數量。

$january = DB::table('users') 
     ->join('bookings', 'users.id', '=', 'bookings.user_id') 
     ->join('accounts', 'users.id', '=', 'accounts.user_id') 
     ->orderBy('users.room_id','asc') 
     ->groupBy('users.id') 
     ->whereYear('bookings.bookingdate','=', '2016') 
     ->whereMonth('bookings.bookingdate','=','01') 
     ->whereYear('accounts.accountdate','=', '2016') 
     ->whereMonth('accounts.accountdate','=','01') 
     ->select('users.*', 
      DB::raw("COUNT(case when bookings.breakfast='on' then 1 else null end) AS t_breakfast"), 
      DB::raw("COUNT(case when bookings.lunch='on' then 1 else null end) AS t_lunch"), 
      DB::raw("COUNT(case when bookings.dinner='on' then 1 else null end) AS t_dinner"), 
      DB::raw("SUM(accounts.amount) AS t_amount") 
     ) 
     ->get(); 

    dd($january); 

我的帳戶表: Accounts Table 我的預訂表: Bookings Table

當我運行此查詢它的顯示:

+"t_breakfast": "2" 
+"t_lunch": "2" 
+"t_dinner": "2" 
+"t_amount": "22.00" 

但我需要t_breakfast,t_lunch, t_dinner的數量是:1.但它顯示雙倍。

+0

當你說它顯示雙倍數量,你指的是t_amount? –

+0

嗨,我正在編輯並在我的文章中添加更多細節。請看我的帖子。 –

+0

你解決了你的問題嗎? –

回答

0

當我嘗試一個查詢時,我沒有解決這個問題。然後我嘗試兩個查詢並解決它。

$data = DB::select("SELECT users.id, users.name , users.picture, users.room_id, 
     SUM(CASE WHEN bookings.breakfast='on' THEN 1 ELSE 0 END) AS t_b , 
     SUM(CASE WHEN bookings.lunch='on' THEN 1 ELSE 0 END) AS t_l , 
     SUM(CASE WHEN bookings.dinner='on' THEN 1 ELSE 0 END) AS t_d FROM `users` 
    INNER JOIN 
    `bookings` ON users.id=bookings.user_id AND 
    MONTH(bookings.bookingdate) = $month AND 
    YEAR(bookings.bookingdate) = $year 

    GROUP BY users.id 
    ORDER BY users.room_id ASC"); 

    $datas = []; 
    $data = json_decode(json_encode($data),true); 
    foreach ($data as $key => $value) { 
     $x = []; 
     $x = $value; 
     $x['exp'] = Account::where('user_id',$x['id'])->whereMonth('accountdate','=',$month)->whereYear('accountdate','=',$year)->sum('amount'); 
     $datas[] = $x; 
    } 

    $total_t_b = $total_t_l = $total_t_d = $total_exp = 0; 
    foreach ($datas as $data) { 
     $total_t_b += $data['t_b']; 
     $total_t_l += $data['t_l']; 
     $total_t_d += $data['t_d']; 
     $total_exp += $data['exp']; 

    } 
    $g_total = $total_t_b + $total_t_l + $total_t_d; 

    if($g_total <= 0) { 
     $perbookingprice = 0; 
    } else { 
     $perbookingprice = $total_exp/$g_total; 
    }