2016-09-20 151 views
1

我有2個SQL表格:一個代表遊覽,另一個代表那些遊覽的預訂。結構如下:雄辯有問題

tours 
(int) id 
(int) max_participants 
(int) state 

bookings 
(int) id 
(fk) tour 
(fk) date 
(int) num_passengers 

的預訂表有一個日期FK,但該表是非常簡單的,而不是重要的,因爲它沒有給我任何麻煩。

現在我需要過濾我的旅行團,只向客戶展示可以容納他所需乘客人數的旅行團。因此,假設一次旅行的最多參與人數爲50人,並且在某個日期的幾次預訂中已經有48個num_passengers,我必須拒絕額外預訂3位乘客(因爲48 + 3> = 50),但是接受另外預訂的2位乘客(如48 + 2> = 50)。

我想出了這個SQL和它的偉大工程(一些值是硬編碼的可讀性,但他們使用變量):

select * from `tours` where `state` = 1 
and exists (select * from `bookings` where `bookings`.`tour` = `tours`.`id` and `date` = 280 having SUM(num_passengers) + 2 <= `tours`.`max_participants`) 

當我嘗試做的雄辯,我得到這個遠:

$tours = Tour::where('state', 1) 
->whereHas('toursBookings', function ($query) use ($request, $date) { 
    return $query->where('date', $date->id) 
     ->havingRaw('SUM(num_passengers) + ' . $request->get('filter_number_passengers') . ' <= ?', [50]); 
}) 
->get(); 

作品像一個魅力,並做它應該做的一切,但數字50是硬編碼!這是一個嚴重的問題,因爲每個巡視的最大參與者數量不同。

任何人都可以找出一種方法來解決這個問題,並解除50的硬編碼?它應該是toursmax_participants與SQL中一樣。

+0

你可以通過變量'$ max_participants'就像'$ date'。對 ? – jaysingkar

回答

1

如果我理解正確的話,你可以做這樣的事情

$max_participants = [50]; 
$tours = Tour::where('state', 1) 
->whereHas('toursBookings', function ($query) use ($request, $date,$max_participants) { 
    return $query->where('date', $date->id) 
     ->havingRaw('SUM(num_passengers) + ' . $request->get('filter_number_passengers') . ' <= tours.max_participants'); 
}) 
->get(); 
+0

好吧,不完全是因爲$ max_participants是tours表中的一個字段,所以它需要從tour更改爲tour。讓我們假設tour1的max_participants爲50,tour2的max_participants爲30,tour3_的max_participants爲90.雄辯需要使用正確的值,而不是硬編碼的值... –

+0

在這種情況下,可以直接把列名有 – jaysingkar

+0

這是絕對正確的!非常感謝 :-) –