php - Laravel chaining scope queries -
i have 2 scope queries db.
the data query looks this:
{ year: "2015", term: "summer", subject_code: "digm", course_no: "350", instr_type: "lab", instr_method: "face 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 internet , playing computer games, lectures, assigned readings, class screening, , research projects, class explores impact of digital media on art, design , daily living. writing intensive course. ", pre_reqs: "", co_reqs: "" } search looks items based on user input, name of course, or instructors
/** * search 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 . '%') ; } the following scope queries returns lectures. tried query this: $class->lectures()->get() , works - pulls lectures.
public function scopelectures($query) { return $query ->where('instr_type', 'like', lecture) // lecture constant ; } however, if chain scope queries together:
$class::search('digm 350')->lecture()->get();
i results of search instead of search->lab.
not quite sure why.
the reason ors in search. when apply both scopes query generated is:
where `course_title` ? or subject_code || ' ' || course_no ? or `instructor` ? , `instr_type` ? while need is
where (`course_title` ? or subject_code || ' ' || course_no ? or `instructor` ? , `instr_type` ?) notice constraints first scope have been put in parentheses.
you need change way apply constraints in search scope:
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 . '%'); }); }
Comments
Post a Comment