laravel - 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 不返回任何内容,因此搜索结果是空白的。我假设我必须在三元运算符的第二部分更改某些内容,但无法弄清楚应该是什么。
解决方案
您可以使用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.'%');
}
推荐阅读
- r - R Shiny 将来自多个动态生成的 textAreaInput 字段的用户输入存储在服务器部分的对象中
- mysql - MySQL显示未加入的结果
- python - 如何访问由循环创建的输入框的更改值 [Tkinter,Python 3.7]
- python - subplot AttributeError:“AxesSubplot”对象没有属性“get_extent”
- python - Matplotlib-获取轴号以在对数图上正确显示
- html - 简单的问题 HTML/CSS 不起作用
- selenium - 如何处理点击我键入的网页上的动态链接
- tensorflow - 分布式 TensorFlow:谁应用参数更新?
- asp.net - 在 EF6 中插入嵌套集合时违反外键(数据库优先)
- java - 如何使用 Java 和 Spark SQL 打印数据集中的行内容?