我的搜索表单有一个 SQL 查询。
$term = $request->get('term');
$queries = Article::where('title', 'LIKE', '%' . $term . '%')->published()->get();
我的研究正在发挥作用。如果我有一篇名为“my great article is awesome”的文章,并且我在搜索表单中写了“great article”,它就有效。
但是如果我写“article awesome”,这些词不会互相跟随,而且它不起作用。
如何让我的查询仅使用关键字?
谢谢
最佳答案
您可以执行如下操作:
$term = $request->get('term');
$keywords = explode(" ", $term);
$article = Article::query();
foreach($keywords as $word){
$article->orWhere('title', 'LIKE', '%'.$word.'%');
}
$articles = $article->published()->get();
如果您只想要包含查询中所有单词的结果,只需将 orWhere
替换为 where
。
如果你想过滤掉某些词,你可以添加如下内容:
$filtered = ["a", "an", "the"];
$filteredKeywords = array_diff($keywords, $filtered);
或者,如果你想更动态,你可以传递一个闭包:
$filteredKeywords = array_filter($keywords, function($word) {
return strlen($word) > 2;
});
关于php - 如何让我的 SQL 查询搜索句子中的几个单词,即使它们不相互跟随,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44036178/