![](/img/trans.png)
[英]What's the best way to implement typo correction into a search in php/mysql?
[英]What is the best way to implement search and filter in a simple code?
目前,我正在使用nicolaslopezj/searchable進行 Laravel 搜索。
搜索很好,但我還想添加一個過濾器和我的過濾器,例如性別、班級或位置。
例如在這種情況下:
1 --- Jane Doe --- F --- A 級 --- 美國
2 --- John Doe --- M --- B 類 --- PH
我目前的代碼是這樣的:
if (isset ($keyword) )
$voters = Voter::search($request->keyword)->paginate(10);
if (isset ($keyword) && isset($request->sex))
$voters = Voter::search($request->keyword)->where('sex', $request->sex)->paginate(10);
if ( !isset($keyword) && isset($request->sex))
$voters = Voter::where('sex', $request->sex)->paginate(10);
if( isset($keyword && !isset($request->sex)
$voters = Voter::search($request->keyword)->paginate(10);
那么知道如何最小化很多條件嗎? 是否有單行代碼/查詢?
您可以使用Model::query()
和Request::has()
方法來檢查請求.. 例如..
$voters = Voter::query();
if ($request->has('keyword'))
$voters = $voters->search($request->keyword);
if ($request->has('sex'))
$voters = $voters->where('sex', $request->sex);
$voters = $voters->paginate(10);
我優化了你的代碼:
$voters = Voter::on();
if (isset ($request->keyword))
$voters = $voters->search($request->keyword);
if (isset($request->sex))
$voters = $voters->where('sex', $request->sex);
$voters = $voters->paginate(10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.