我正在尝试在我的网站上构建搜索(使用 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);
注意:使用此代码我可以按类别和工作获取个人资料,但我无法按城市和位置检索个人资料! 感谢您的帮助;
最佳答案
您可以简单地使用查询构建器或 Eloquent 来完成,请注意,查询构建器中可用的任何功能也可用于 Eloquent 查询, 为了简单起见,我已经在查询构建器方法中给出了答案,
$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();
关于php - 用搜索 Eloquent 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38588776/