php - 用搜索 Eloquent 过滤

标签 php mysql laravel eloquent

我正在尝试在我的网站上构建搜索(使用 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/

相关文章:

php - Codeigniter 使用事件记录选择自定义

jquery - 在 Laravel 文件夹中将 Twitter Bootstrap 或 Jquery UI 等第三方资源放在哪里?

php - Angular 6 HttpClient 和 PHP 错误 (unknown url) : 0 Unknown Error 的 Http 失败响应

php - 选择同一页面的 DIV 内容并将其显示在 PHP 的同一页面上

php - 用于删除具有重复条目的行的 MySQL 查询

MySQL:单连接还是多连接?

php - 使用mysql存储过程创建分页

php - 在我的 WordPress 导航菜单中插入设计元素

php - Laravel Eloquent 通过 id 删除

.htaccess - Laravel + AngularJS 将路由传递给 Angular