如何使我的SQL查询在句子中搜索几个单词,即使它们不相互跟随

Jer*_*emy 5 php mysql laravel eloquent laravel-eloquent

我的搜索表单有一个SQL查询.

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

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

我的研究正在进行中.如果我有一篇名为"我的伟大文章很棒"的文章,并且我在我的搜索表单中写了"greate article",它就可以了.

但是,如果我写"文章真棒",这些词语就不会互相影响,而且它不起作用.

如何使我的查询仅使用关键字?

谢谢

Ale*_*ris 8

您可以执行以下操作:

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

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

$articles = $article->published()->get();
Run Code Online (Sandbox Code Playgroud)

如果只想要包含查询中所有单词的结果,则只需替换orWherewith where.

如果你想过滤掉某些单词,你可以添加如下内容:

$filtered = ["a", "an", "the"];
$filteredKeywords = array_diff($keywords, $filtered);
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要更加动态,可以传递一个闭包:

$filteredKeywords = array_filter($keywords, function($word) {
    return strlen($word) > 2;
});
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案.当我看到这个答案时,实际上写的是同样的事情.+1 (3认同)