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

标签 php mysql laravel eloquent

我的搜索表单有一个 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/

相关文章:

php - 如何从类(class)最新测试中选择最佳成绩

mysql - 改进查询以根据没有联合的值连接其他表

mysql - MySQL语法错误

php - 从多维数组中获取键值

php - 给出参数 php 函数以在另一个文件中显示数据库结果

javascript - 使用 AngularJS 和 php 将数据从表单保存到数据库

php - 令人困惑的mysql问题

php - 将我的 Laravel 连接到外部数据库

php - Laravel Eloquent 内部连接自引用表

php - Laravel - 无效参数编号 : parameter was not defined