简体   繁体   English

如何使我的SQL查询搜索句子中的多个单词,即使它们彼此不跟随

[英]How to make my SQL query search several words in the sentence even if they do not follow each other

I have a SQL query for my search form. 我的搜索表单有一个SQL查询。

$term = $request->get('term');

$queries = Article::where('title', 'LIKE', '%' . $term . '%')->published()->get();

My research is working. 我的研究正在进行。 If I have an article called "my great article is awesome" and that I write in my search form "greate article" it works. 如果我有一篇名为“我的很棒的文章很棒”的文章,并且我以搜索形式“伟大的文章”撰写,那么它会起作用。

But if I write "article awesome", the words do not follow each other, and it does not work. 但是,如果我写的是“很棒的文章”,这两个词就不会互相跟随,而且行不通。

How do I get my query to work just with keywords? 如何使查询仅与关键字一起使用?

Thank you 谢谢

You can do something like follows: 您可以执行以下操作:

$term = $request->get('term');
$keywords = explode(" ", $term);

$article = Article::query();
foreach($keywords as $word){
    $article->orWhere('title', 'LIKE', '%'.$word.'%');
}

$articles = $article->published()->get();

If you want only results that contain all the words in the query just replace the orWhere with where . 如果只需要包含查询中所有单词的结果,则将orWhere替换为where

If you want to filter out certain words you could add something like: 如果要过滤掉某些单词,可以添加以下内容:

$filtered = ["a", "an", "the"];
$filteredKeywords = array_diff($keywords, $filtered);

Alternatively you can pass a closure if you want to be more dynamic: 另外,如果您想提高动态性,则可以传递闭包:

$filteredKeywords = array_filter($keywords, function($word) {
    return strlen($word) > 2;
});

why don't you try something like that 你为什么不尝试这样的事情

$search = "article awesome";
$search = preg_replace("#\s+#", '%', $search);

replacing spaces with '%' will resolve the case you mentioned 用'%'替换空格将解决您提到的情况

if you want to make the search ignoring the words order this should work 如果您要进行搜索而忽略单词order,则应该可以

$search = trim(" article awesome great ");
$search = preg_split("#\s+#", $search);
$where =  "WHERE column like '%" .  implode( "%' AND column like '%", $search ) . "%'";

however it will take more execution time and resources on the server, 但是,这将花费更多的执行时间和服务器上的资源,

also think to add some injection escaping to avoid sql syntax errors 也认为添加一些注入转义以避免sql语法错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM