首页 > 解决方案 > Laravel 中的范围搜索从空请求()返回所有结果

问题描述

我正在使用 Scope Search,但无法弄清楚为什么我的三元运算符会像现在这样工作。

在我看来,我有以下几点:

<form action='/search-results' method='GET'>

{{ csrf_field() }}

<div style="background-color:white">

<div class="container py-5">
    <div class="input-group custom-search-form md-form mt-0">
                <input type="text" class="form-control" name="city" placeholder="City...">
                <input type="text" class="form-control" name="search" placeholder="Search...">
                <span class="input-group-btn">
    <button class="btn btn-default-sm" type="submit">
        Submit
    </button>
</div>
</div>
</div>
</form>

我的控制器中有以下内容:

    public function index()
{

    {
        //The search() function is accessed using 'scopeSearch' within NPIData Model


        $providers = NPIData::lookup()->orderBy('NPI')->paginate(20);

        return view('inc.searchresults', compact('providers'));
    }

我的 NPIData 模型中有以下内容:

    public function scopeLookup($query)
{


    //this says if the request is NOT empty, return $query (which would be an empty query), otherwise return $query with all the conditions listed

    return empty(request())  ? $query :  $query->where('NPI', 'like', '%'.request()->search.'%')
                                                ->where('Entity Type Code', '=', '1')
                                                ->where('Provider Business Mailing Address City Name', '=', request()->zip)
                                                ->orWhere('Provider First Name', 'like', '%'.request()->search.'%')
                                                ->orWhere('Provider Last Name (Legal Name)', 'like', '%'.request()->search.'%');

                                            }

}

当在“城市”和“搜索”文本输入中输入搜索词时,$query 会正确执行。但是,如果一个或两个输入都留空,$query 将返回我的 NPIData 表中的所有内容。如果一个或两个输入都留空,我希望我的 $query 不返回任何内容,因此搜索结果是空白的。我假设我必须在三元运算符的第二部分更改某些内容,但无法弄清楚应该是什么。

标签: laravel

解决方案


您可以使用where 1 < 0这是获得空结果的标准方法

public function scopeLookup($query)
{
    //this says if the request is NOT empty, return $query (which would be an empty query), otherwise return $query with all the conditions listed

    return empty(request()) ? $query->whereRaw('1 < 0') : $query->where('NPI', 'like', '%'.request()->search.'%')
        ->where('Entity Type Code', '=', '1')
        ->where('Provider Business Mailing Address City Name', '=', request()->zip)
        ->orWhere('Provider First Name', 'like', '%'.request()->search.'%')
        ->orWhere('Provider Last Name (Legal Name)', 'like', '%'.request()->search.'%');
}

推荐阅读