我目前正在尝试在我的数据库中实现关键字/标签的搜索。
在我的数据库中,我有一些带有关键字的行,例如:
auto,cabrio,frischluft
或者
hose,jeans,blaue hose,kleidung
所以总是有一些关键字(基本上也可以有空格),用逗号分隔( ,
)。
现在我希望能够在我的数据库中找到输入了一些关键字的产品。
与 LIKE
我可以通过类似 auto,cabrio
的查询找到我提到的两个条目或者也cabrio,frischluft
或hose,jeans,blau
或hose,kleidung
。但是如果我输入 auto,frischluft
会发生什么?或类似hose,blaue hose
或jeans,kleidung
?
然后LIKE
不再工作了。有没有办法做到这一点?
我希望你明白我的意思...
所以为了清楚起见:我当前使用的代码是:
$searchQuery = "%".$request->input('productSearch')."%";
和$products = Product::where('name', 'LIKE', $searchQuery)->paginate(15);
但正如我所说,这不会让我返回带有关键字 auto,cabrio,frischluft
的文章如果输入productSearch
有关键字auto,frischluft
输入...
有什么想法吗?
最佳答案
抱歉,我知道我参加聚会迟到了,但这是我在寻找 Eloquent 关键字搜索时 Google 中的第一个结果。我遇到了同样的问题,我想帮助解决我的问题。
$q = $request->input('productSearch');
$needles = explode(',', $q);
// In my case, I wanted to split the string when a comma or a whitespace is found:
// $needles = preg_split('/[\s,]+/', $q);
$products = Products::where('name', 'LIKE', "%{$q}%");
foreach ($needles as $needle) {
$products = $products->orWhere('name', 'LIKE', "%{$needle}%");
}
$products = $products->paginate(15);
如果用户输入的逗号太多,则 $needles
数组可能太大(并且查询太大),因此您可以限制搜索,例如,仅搜索前 5 个数组中的元素:
$needles = array_slice($needles, 0, 5);
我希望这可以帮助别人。
关于php - Laravel Eloquent/SQL - 在数据库中搜索关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42052914/