:)
我為想要瀏覽招聘資訊的用戶實作了一個搜索功能,它看起來像這樣:
https://i.stack.imgur.com/wGcW6.png
它的代碼如下所示:
public function index(Request $request)
{
if ($word = $request->get('s')) {
$postsQuery = $postsQuery
->where('titel', 'like', "%{$word}%")
->where('isActive', 1)
->where('is_Canceled', 0)
->orWhere('id', '=', $word);
}
if ($location = $request->get('standort') and $request->get('standort') != 'alle') {
$postsQuery = $postsQuery->where('Standort', $location);
}
if ($dep = $request->get('abteilung') and $request->get('abteilung') != 'alle') {
$postsQuery = $postsQuery->where('abteilung_name', $dep);
}
$posts = $postsQuery->orderBy('titel')->get();
if ($posts->count() == 0) {
return view('posts.overview', ['posts' => $posts, 'standorts' => $standorts, 'abteilungs' => $abteilungs])
->withErrors(['error' => 'Es wurde kein Treffer gefunden, versuchen Sie es mit anderen Suchparametern']);
}
return view('posts.overview', ['posts' => $posts, 'standorts' => $standorts, 'abteilungs' => $abteilungs]);
}
我的問題是只搜索一個引數。因此,當用戶輸入搜索詞“IT” 位置 (Standort) 或部門 (Abteilung) 時,只會搜索搜索詞。
我在 2 個小時內嘗試了無數不同的東西,但我就是無法讓它發揮作用。如果您有任何提示,請告訴我!
編輯:當我忽略orWhere('id', '=', $word)它時,它可以作業,但我必須把它留在里面。但我不能將它更改為正常,where()因為它不會回傳任何匹配項。
uj5u.com熱心網友回復:
你做了:
where a and b and c or d
但你想要:
where (a and b and c) or d
https://laravel.com/docs/8.x/queries#logical-grouping
所以粗略地說,你應該努力構建這樣的東西:
$posts = Post::query()
->where(function (Builder $query) {
$query->where('clauseA', '=', 1)
->where('clauseB', '=', 2)
->where('clauseC', '=', 3);
})
->orWhere('id', '=', $word)
->get();
uj5u.com熱心網友回復:
public function index(Request $request)
{
if ($word = $request->get('s')) {
if (is_numeric($word)) {
$postsQuery = $postsQuery
->where('id', '=', $word)
->where('isActive', 1)
->where('is_Canceled', 0);
} else {
$postsQuery = $postsQuery
->where('titel', 'like', "%{$word}%")
->where('isActive', 1)
->where('is_Canceled', 0);
}
}
if ($location = $request->get('standort') and $request->get('standort') != 'alle') {
$postsQuery = $postsQuery->where('Standort', $location);
}
if ($dep = $request->get('abteilung') and $request->get('abteilung') != 'alle') {
$postsQuery = $postsQuery->where('abteilung_name', $dep);
}
$posts = $postsQuery->orderBy('titel')->get();
if ($posts->count() == 0) {
return view('posts.overview', ['posts' => $posts, 'standorts' => $standorts, 'abteilungs' => $abteilungs])
->withErrors(['error' => 'Es wurde kein Treffer gefunden, versuchen Sie es mit anderen Suchparametern']);
}
return view('posts.overview', ['posts' => $posts, 'standorts' => $standorts, 'abteilungs' => $abteilungs]);
}
這不是一個優雅的解決方案,但我只是檢查搜索詞是數字還是單詞,然后繼續進行相應的條件和搜索功能
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406107.html
標籤:
