我的数据库有两个范围查询。
我查询的数据如下所示:
{
year: "2015",
term: "Summer",
subject_code: "DIGM",
course_no: "350",
instr_type: "Lab",
instr_method: "Face To Face",
section: "003",
crn: "42953",
course_title: "Digital Storytelling",
credits: "3.0",
day: "R",
time: "06:30 pm - 09:20 pm",
instructor: "Teacher Name",
campus: "University Building",
max_enroll: "18",
enroll: "18",
building: "PLACE",
room: null,
description: "By surfing the internet and playing computer games, by lectures, assigned readings, class screening, and research projects, this class explores the impact of digital media on art, design and daily living. This is a writing intensive course. ",
pre_reqs: "",
co_reqs: ""
}
search
只根据用户输入查找项目,就像课程名称或教师一样
/**
* Search for course title or subject name
* @param $query
* @param $searchTerm Course Title or Subject Name i.e. "ECEC 355" or
* "Digital Logic"
* @return mixed
*/
public function scopeSearch($query, $searchTerm) {
return $query
->where('course_title', 'like', '%' . $searchTerm . '%')
->orWhere(DB::raw("subject_code || ' ' || course_no"),
'like',
'%' . $searchTerm . '%'
)
->orWhere('instructor', 'like', '%' . $searchTerm . '%')
;
}
以下范围查询仅返回讲座。我尝试过这样的查询:$class->lectures()->get()
并且它有效 - 它可以完成所有讲座。
public function scopeLectures($query) {
return $query
->where('instr_type', 'like', LECTURE) // where LECTURE is a constant
;
}
但是,如果我将范围查询链接在一起:
$class::search('digm 350')->lecture()->get();
我会得到search
而不是search->lab
的所有结果。
不太确定原因。
答案 0 :(得分:3)
原因是您在搜索中执行的操作系统。应用两个范围时,生成的查询为:
where `course_title` like ? or subject_code || ' ' || course_no like ? or `instructor` like ? and `instr_type` like ?
而你需要的是
where (`course_title` like ? or subject_code || ' ' || course_no like ? or `instructor` like ? and `instr_type` like ?)
请注意,第一个范围的约束已放在括号中。
您需要更改搜索范围中的约束应用方式:
public function scopeSearch($query, $searchTerm) {
return $query->where(function($query) use ($searchTerm) {
$query
->where('course_title', 'like', '%' . $searchTerm . '%')
->orWhere(DB::raw("subject_code || ' ' || course_no"), 'like', '%' . $searchTerm . '%')
->orWhere('instructor', 'like', '%' . $searchTerm . '%');
});
}