laravel 5.2 search query

我是研究僧i 提交于 2019-12-25 09:05:44

问题


Here is the most recent problem I have ran into. I'm trying to implement search into my application and I know how to do it when it comes to searching your tables for keywords with where('firstname', 'LIKE', %$search%) and such. However, how would I go about narrowing down a search based on what criteria the user specifies. For exlample search for $keyword but also a $city and $pricePoint.

I'm just trying to figure out how to structure the query in php so that if user specifies the $keyword and the city it searches for that, and if user only specifies the $keyword, the city aspect of the query is not present.

Project is build on Laravel 5.2 and mysql database. Any help is appreciated.


回答1:


Suppose there are 3 criteria: $keyword, $city and $pricePoint. You can do:

$query = DB::table('users');
if (!empty($keyword)) {
    $query = $query->where('keyword', 'LIKE', '%'.$keyword.'%');
}
if (!empty($city)) {
    $query = $query->where('city', 'LIKE', '%'.$city.'%');
}
if (!empty($pricePoint)) {
    $query = $query->where('pricePoint', 'LIKE', '%'.$pricePoint.'%');
}
$results = $query->get();

Then you can of course make something more generic by doing a list of criteria and iterating through them with a loop instead of adding another if conditions.



来源:https://stackoverflow.com/questions/40186017/laravel-5-2-search-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!