使用搜索功能进行筛选
问题描述:
我正在尝试在我的网站上创建搜索(使用laravel 5.2)。我需要一次搜索多个表格。基本上我需要通过筛选类别,工作,部门和城市来显示个人资料信息!使用搜索功能进行筛选
profiles : id, name, ......, job_id, location_id......
location : id, name, city_id
job : id, name, categorie_id
categorie : id, name
city : id, name
in below code :
$profils = \App\Profils::whereHas('jobs', function($query){
$nom_catego = \Input::has('lcategorie') ? \Input::get('lcategorie') : null;
$nom_job = \Input::has('ljob') ? \Input::get('ljob') : null;
$nom_location = \Input::has('ldept') ? \Input::get('llocation') : null;
if(!isset($nom_catego) && !isset($nom_job)){
$query->where('categorie_id', '=' , $nom_catego)
->where('id', '=', $nom_job);
}
if(!isset($nom_catego) && isset($nom_job)){
$query->where('categorie_id', '=' , $nom_catego);
}
if(!isset($nom_job) && !isset($nom_location) && isset($nom_catego)){
$query->where('city_id', '=' , $nom_location)
->where('id', '=' , $nom_catego);
}
if(isset($nom_job) && !isset($nom_location) && isset($nom_catego)){
$query->where('city_id', '=' , $nom_location);
}
})->paginate(10);
注意:使用此代码我可以按类别和作业获取配置文件,但无法通过城市和位置检索配置文件! 谢谢你的帮助;
答
,你可以简单地查询生成器或雄辩做到这一点,需要注意的是不论在查询生成器提供的功能可用于雄辩查询过, 我已经给定在简单查询生成器方法的答案,
$results = DB::table('profiles')
->select(['profiles.*']);
if($request->has('lcategorie')){
$results->join('job','profiles.job_id','=','job.id');
$results->join('categorie','job.categorie_id','=','categorie.id');
$results->where('categorie.id','=',$request->input('lcategorie'));
}
if($request->has('ljob')){
if(!$request->has('lcategorie')){ //avoid repeat the join to same table multiple time
$results->join('job','profiles.job_id','=','job.id');
}
$results->where('job.id','=',$request->input('ljob'));
}
if($request->has('ldept')){
$results->join('location','profiles.location_id','=','location.id');
$results->join('city','location.city_id','=','city.id');
$results->where('location.id','=',$request->input('llocation'));
}
$results = $results->get();
答
谢谢阿克拉姆,它的工作原理还增加了按城市过滤如下:
if($request->has('ldept')){
$profiles->join('location','profiles.location_id','=','location.id');
$profiles->join('citys','location.city_id','=','citys.id');
$profiles->where('citys.id','=',$request->input('ldept'));
}
if($request->has('llocation')){
if(!$request->has('ldept')){
$profiles->join('location','profiles.location_id','=','location.id');
}
$profiles->where('location.id','=',$request->input('llocation'));
}
谢谢你的回复; 我更喜欢使用雄辩。 与查询生成器我遇到此错误:未定义变量:请求 – nabil
您必须在您的控制器中实例化请求$请求。 '公共功能保存(Request $ request){}' –