【问题标题】:Using Laravel eloquent to search if a value in a database column appears in search string使用 Laravel eloquent 搜索数据库列中的值是否出现在搜索字符串中
【发布时间】:2019-08-13 19:12:04
【问题描述】:

我目前正在从事一个 laravel 5.4 项目,我试图在我的数据库中找到类似于引入的搜索字符串的值。例如,我有以下搜索词

$search_term = "Some long phrase with words"

在我的数据库 (MySQL) 中,我有一个表 tags,其中有一列 value。此表中的一行可能有value => 'some',另一行可能有value => 'long',另一行可能有value => 'phra'

我需要创建一个包含value 出现在我的搜索词中的所有标签的集合。这意味着我提到的 3 行应该与我的 $search_term 匹配

我目前知道我可以在 laravel 中使用 eloquent 并说类似

Tag::where('value', 'like', "%".$search_term."%")->get()

但据我了解,这将查看 $search_term 是否是 value 列中内容的子字符串。

如何使用 eloquent 询问 value 是否包含在 $search_term 中(子字符串)?

【问题讨论】:

  • 使用 PHP 将您的搜索词拆分为单个词的数组。然后使用->whereIn('tag', $words)

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

您可以使用正则表达式搜索 REGEXP。但是,由于您要将字段与变量进行比较,因此您将不得不稍微切换一下并使用原始查询:

 TAG::whereRaw('? REGEXP value', [$search_term])->get();

【讨论】:

  • 你的意思是 REGEXP 是一个关键字还是我需要在这里输入我的正则表达式?
  • REGEXP 是关键字/运算符,就像 LIKE 一样。
  • 'scary search term' REGEXP 'car' 将返回 TRUE。
【解决方案2】:

我知道你要求一个雄辩的解决方案,但也许只是用 php 解决它?你可以这样做:

$tags = Tag::all();
$tags_found = collect([]);

foreach($tags as $tag) {
    if(strpos($search_term, $tag->value) !== false)
        $tags_found->push($tag)
}

【讨论】:

    【解决方案3】:

    使用 PHP 将您的搜索词拆分为单个单词的数组。

    $search_term = "Some long phrase, with words!";
    
    $words = preg_replace('/\W+/', ' ', $search_term);
    $words = trim($words);
    $words = explode(' ', $words);
    

    现在$words 包含

    array (
      0 => 'Some',
      1 => 'long',
      2 => 'phrase',
      3 => 'with',
      4 => 'words',
    )
    

    你可以用

    搜索
    Tag::whereIn('value', $words)->get();
    

    注意:preg_replace('/\W+/', ' ', $search_term); 将用一个空格替换任何非单词字符序列。

    【讨论】:

    • 我的问题是我不能保证数据库中的值是一个词。考虑到上下文,这个值可能是一个短语,而不仅仅是一个词......
    【解决方案4】:

    我更喜欢这个,因为不是每个字符串都是有效的正则表达式。

    TAG::whereRaw('? LIKE CONCAT("%", value, "%")',
        [$search_term])->get();
    

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多