在laravel 5中搜索belongsToMany关系

时间:2016-04-12 16:56:16

标签: php mysql laravel-5 eloquent relationship

实际上我想在选择任何科目或课程后搜索用户想要搜索的那些问题。

如果从主题或课程中移除whereHas,则其工作但两者都不起作用。

请提供更好的解决方案,以便在belongsToMany实现中进行搜索。

我有一个Question模型类

的问题表
class Question extends Model{
    public function courses(){
        return $this->belongsToMany('App\Models\Course','course_questions');
    }

    public function subjects(){
        return $this->belongsToMany('App\Models\Subject','subject_questions');
    }
}

并在我的searchController

public function index(Request $request){
        $questions = Question::with(['user','courses','branches','subjects','years','universities','question_type'])
            ->where("status","=",1)
            ->where(function($query) use($request){
                $q = $request->q;
                if(isset($q) && !is_null($q)){
                    $query->where("question","LIKE","%$q%");
                }
            })
            ->whereHas('subjects',function($query) use($request){
                $subjects = $request->subject;
                if(isset($subjects)){
                    $_subjects = explode(" ",$subjects);
                    $query->whereIn("slug",$_subjects)
                    ->orWhereIn("subject_name",$_subjects);
                }
            })
            ->whereHas('courses',function($query) use($request){
                $course = $request->course;
                if(isset($course)){
                    $_course = explode(" ",$course);
                    $query->whereIn("slug",$_course)
                        ->orWhereIn("course",$_course);
                }
            })
            ->paginate();
        if($request->ajax()){
            $returnHTML = view('questions.question_list')->with('questions', $questions)->render();
            return response()->json(array('success' => true, 'pageContent'=>$returnHTML));
        }

1 个答案:

答案 0 :(得分:4)

您应该以这种方式构建查询 - 您应该在向查询添加任何约束之前验证条件:

$query = Question::with(['user','courses','branches','subjects','years','universities','question_type'])
            ->where("status","=",1);

$q = $request->q;
if(isset($q) && !is_null($q)) {
    $query = $query->where("question","LIKE","%$q%");
}

$subjects = $request->subject;
if (isset($subjects)) {
    $query = $query->whereHas('subjects',function($query) use($subjects){                
        $_subjects = explode(" ",$subjects);
        $query->whereIn("slug",$_subjects)
       ->orWhereIn("subject_name",$_subjects);                
   });
}

$course = $request->course;
if (isset($course)) {
    $query = $query->whereHas('courses',function($query) use($course ){       
        $_course = explode(" ",$course);
        $query->whereIn("slug",$_course)
       ->orWhereIn("course",$_course);
    });
}

$questions = $query->paginate();