我尝试按名称和/或类别和/或位置和/或月份建立高级搜索,但是我有一个无法解决的问题,这是控制器;
$searchName = $advancedSearchData['search_name'];
$searchCategory = $advancedSearchData['search_category'];
$searchLocation = $advancedSearchData['search_location'];
if(!empty($searchName)) {
$allCourses = Courses::where('course_name', 'like', '%'.$searchName.'%') -> get();
}
if($searchCategory !== 0) {
$allCourses = Courses::where('course_name', 'like', '%'.$searchName.'%') -> where(['category_id' => $searchLocation]) -> get();
}
if($coursesLocation !== 0) {
$allCourses = Courses::where('course_name', 'like', '%'.$searchName.'%') -> where(['location' => $searchLocation]) -> get();
}
return view('layouts.public_layouts.courses.courses_search') -> with(compact('allCourses'));
答案 0 :(得分:0)
您可以尝试
$allCourses = Courses::where(function($query) use ($advancedSearchData) {
if(isset($advancedSearchData['search_name'])){
$query->where('course_name', 'like', '%'.$advancedSearchData['search_name'].'%');
}
if(isset($advancedSearchData['search_category']))){
$query->where(['category_id' => $advancedSearchData['search_category']);
}
if(isset($advancedSearchData['search_location']))){
$query->where(['location' => $advancedSearchData['search_location']);
}
})
->get();
答案 1 :(得分:0)
您可以尝试一下。我不知道问题到底是什么,但是我可以看到问题。在高级搜索中,您必须在代码末尾使用->get()
。这样,您可以在执行之前将任何条件添加到查询中。
$allCourses = new Course();
$allCourses = $allCourses->newQuery();
$searchName = $advancedSearchData['search_name'];
$searchCategory = $advancedSearchData['search_category'];
$searchLocation = $advancedSearchData['search_location'];
if(!empty($searchName)) {
$allCourses = $allCourses->where('course_name', 'like', '%'.$searchName.'%');
}
if($searchCategory !== 0) {
$allCourses = $allCourses->where('course_name', 'like', '%'.$searchName.'%') -> where(['category_id' => $searchLocation]);
}
if($coursesLocation !== 0) {
$allCourses = $allCourses->where('course_name', 'like', '%'.$searchName.'%') -> where(['location' => $searchLocation]);
}
$allCourses = $allCourses->get();
return view('layouts.public_layouts.courses.courses_search') -> with(compact('allCourses'));
答案 2 :(得分:0)
我认为您将面临的问题是未定义的索引,因此您必须首先检查数组索引,例如:
$searchName = $advancedSearchData['search_name'] ?? null;
$searchCategory = $advancedSearchData['search_category'] ?? null;
$searchLocation = $advancedSearchData['search_location'] ?? null;
$query = (new Course())->newQuery();
if($searchName) {
$query->where('course_name', 'like', '%'.$searchName.'%');
}
if($searchCategory) {
$query->where('course_name', 'like', '%'.$searchName.'%') -> where(['category_id' => $searchLocation]);
}
if($coursesLocation) {
$query->where('course_name', 'like', '%'.$searchName.'%') -> where(['location' => $searchLocation]);
}
$allCourses = $query->get();
return view('layouts.public_layouts.courses.courses_search')->with(compact('allCourses'));