Laravel 多重过滤器与搜索

我想搜索服务提供商和产品,并按位置和服务或按位置和副产品进行过滤。我正在使用下面的代码` $results = new ClientProfile;


    if (request()->has('service-provider')) {

        $results = $results->where('jobsc_id', request('service-provider'));

    } elseif(request()->has('product')) {

        $results = $results->where('product_id', request('product'));

    } elseif(request()->has('city')){

        $results = $results->where('divsec_id', request('city'));

    } else {

        $results = ClientProfile::searched();

    }  

    

    $results = $results->where('profile_state', 'active')->paginate(10)->appends([

        'service-provider' => request('service-provider'),

        'product' => request('product'),

        'city' => request('city'),

    ]);

    

            

    return view('results')->with('results', $results);`

虽然它显示的 URL 为domain.com/results?product=2&city=78,但它显示了所有没有按城市过滤的产品


慕沐林林
浏览 111回答 2
2回答

德玛西亚99

因此,当你找到一个时你使用if elseif它,第二个也不会出现。改用when_if else$results = new ClientProfile::when(request()->has('service-provider'), function($q){    $q->where('jobsc_id', request('service-provider'));})->when(request()->has('product'), function($q){    $q->where('product_id', request('product'));})->when(request()->has('city'), function($q){    $q->where('divsec_id', request('city'));})->when(count($request->all()) === 0, function($q){    $q->searched();})->where('profile_state', 'active')->paginate(10)->appends([    'service-provider' => request('service-provider'),    'product' => request('product'),    'city' => request('city'),]);        return view('results')->with('results', $results);`

红颜莎娜

这段代码对我有用$results = ClientProfile::when(request()->has('service-provider'), function($q){            $q->where('jobsc_id', request('service-provider'));        })->when(request()->has('product'), function($q){            $q->where('product_id', request('product'));        })->when(request()->has('city'), function($q){            $q->where('divsec_id', request('city'));        })->when(count(request()->all()) === 0, function($q){            $q->searched();        })->where('profile_state', 'active')->paginate(10)->appends([            'service-provider' => request('service-provider'),            'product' => request('product'),            'city' => request('city'),        ]);
打开App,查看更多内容
随时随地看视频慕课网APP