在laravel 5中搜索belongsToMany关系

编程入门 行业动态 更新时间:2024-10-08 18:34:58
本文介绍了在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关系

本文发布于:2023-11-28 20:22:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   laravel   belongsToMany

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!