2014-11-24 44 views
1

我有一個日曆(FullCalendar),用戶可以根據幾個參數(Tutor Secondary Tutor,Lesson,Location)篩選結果。當用戶對查詢進行更改時,它會碰到以下代碼。Laravel:基於輸入查詢。如果輸入爲空,請獲取全部

我遇到的問題是'OR'。我真正想要的是一個IF輸入爲空然後全部獲得。

如果用戶{獲取所有課程其中lead_tutor_id = 1和secondary_tutors_id = 1} 如果用戶和地點{獲取教訓,其中用戶是如上述,但具有LOCATION_ID = 3} 等,等

所以,如果只設置了一個或兩個過濾器,是否有一種方法可以回退以獲得所有結果?

$current_events = Calendar::Where(function($query) use ($start_time, $end_time, $tutor, $location, $lesson) 
     { 
      $query->whereBetween('date_from', [$start_time, $end_time])->orderBy('date_from') 
       ->whereRaw('lead_tutor_id = ? 
          OR secondary_tutors_id = ? 
          OR location_id = ? 
          OR lesson_id = ?', 
          [ 
           $tutor, // Input get() for user 
           $tutor, // Input get() for user 
           $location, // Input get() for location 
           $lesson, // Input get() for lesson 
          ] 
         ); 
     })->with('lessons', 'leadtutor', 'secondarytutor')->get(); 

我一直在玩查詢範圍,但這似乎失敗,如果傳遞一個NULL值通過它。

任何幫助,非常感謝。提前致謝。

+0

1.你不需要在第一封'where',2。你不需要'whereRaw'可言, 3.你可能需要關閉所有的「或」輪,4.究竟是什麼問題?查詢範圍不會因爲NULL而失敗,因此請重新考慮您的問題。 – 2014-11-24 16:04:39

回答

2

您可以在正手上構建查詢,將其存儲在一個變量中,並在構建它時使用它。

$query = isset($var) ? $var : ''; 
$query .= isset($othervar) ? $othervar : ''; 

whereBetween(*)->orderBy(*)->whereRaw($query) 

只有你需要記住的是在正確的位置插入'OR'。因此,如果沒有,則首先要插入或不插入,然後將「或」放在它的前面。

希望有足夠的信息來幫助你。

+0

謝謝聖天才,是的,工作得很好。但是,如果我混合使用AND和OR,查詢會中斷:'lead_tutor_id = 1或secondary_tutors_id = 1 AND lesson_id = 1 AND location_id = 1'。第二輪在戰鬥中!再次感謝這一點。 – T2theC 2014-11-24 16:18:21

0

從聖天才的意見後,我得到這個工作:

$built_query = []; 
isset($lead_tutor) ? $built_query['lead_tutor'] = 'lead_tutor_id = ' . $lead_tutor . ' ' : null; 
isset($secondary_tutor) ? $built_query['secondary_tutor'] = 'secondary_tutors_id = ' . $secondary_tutor . ' ' : null; 
isset($location_id) ? $built_query['location'] = 'location_id = ' . $location_id : null; 
isset($lesson_id) ? $built_query['lesson'] = 'lesson_id = ' . $lesson_id : null; 

// Flatten the array so we can create a query and add the word ADD in between each element. 
$built_query = implode(" AND ", $built_query); 

// Run the query 
$current_events = Calendar::whereBetween('date_from', [$start_time, $end_time])->orderBy('date_from')->whereRaw($built_query)->with('lessons', 'leadtutor', 'secondarytutor')->get();