本文介绍了在laravel 5中搜索belongsToMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
实际上,我想在选择任何主题或课程后搜索用户要搜索的那些问题.
Actually i want to search those question which user want to search after select any subject or course.
如果从主题或课程中删除 whereHas ,但两者均无法正常工作.
if a remove either whereHas from subject or course its works but with both its not working.
请提供一个更好的解决方案,用于在belongsToMany房地产中进行搜索.
Please give a better solution for searching in belongsToMany realtionship.
我有一个带有 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)); } 推荐答案您应该以这种方式构建查询-在向查询添加任何约束之前,应先验证条件:
You should build your query probably this way - you should verify conditions before adding any constraints to your query:
$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();更多推荐
在laravel 5中搜索belongsToMany关系
发布评论