laravel 5.2搜索查询 [英] laravel 5.2 search query
问题描述
这是我遇到的最新问题.我正在尝试在我的应用程序中实现搜索,当使用where('firstname', 'LIKE', %$search%)
等在您的表中搜索关键字时,我知道该怎么做.但是,我将如何根据用户指定的条件来缩小搜索范围.对于出色的搜索,除了$ keyword之外,还要搜索$ city和$ pricePoint.
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.
我只是想弄清楚如何在php中构造查询,以便如果用户指定$ keyword和它搜索的城市,并且如果用户仅指定$ keyword,则查询的城市方面是不存在.
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.
项目基于Laravel 5.2和mysql数据库构建.感谢您的帮助.
Project is build on Laravel 5.2 and mysql database. Any help is appreciated.
推荐答案
假设有3个条件:$ keyword,$ city和$ pricePoint.您可以这样做:
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();
然后,您当然可以通过列出一系列条件并通过循环遍历这些条件,而不是添加其他if条件,来使事情更通用.
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.
这篇关于laravel 5.2搜索查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!