我尝试使用laravel在我的数据库上使用多个过滤器

时间:2018-06-04 11:18:19

标签: php mysql laravel

我已经尝试过实现多个过滤器,但是每次我根据它运行的过滤器进行过滤,但是当过滤器相对于其他过滤器时,查询只接受一个过滤器。

我的注册控制器:allCandidates



public function allCandidates(){

        $candidates = new Candidate;

        $queries = [];

        $columns = [
            'field', 'qualification',
        ];

        foreach ($columns as $column) {
            if (request()->has($column)) {
                $candidates = $candidates->where($column, request($column));
                $queries[$column] = request($column);
            }
        }
        if (request()->has('sort')) {
            $candidates =$candidates->orderBy('surname', request('sort'));
            $queries['sort'] = request('sort');
        }
        $candidates =$candidates->paginate(10)->appends($queries);
        return view('contact.candidates', compact('candidates'));
    }




1 个答案:

答案 0 :(得分:0)

重写代码如下:

public function allCandidates(){

        $candidates = new Candidate;

        $columns = [
            'field', 'qualification',
        ];

        foreach ($columns as $column) {
            if (request()->has($column)) {
                $candidates->where($column, request($column));
            }
        }
        if (request()->has('sort')) {
            $candidates->orderBy('surname', request('sort'));
        }
        $candidates->paginate(10);
        return view('contact.candidates', compact('candidates'));
    }

一旦完成后,无需重新初始化 $ candidate 变量。只需添加过滤器或使用对象$ candidate。调用另一个函数。