Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用Laravel eloquent搜索数据库列中的值是否出现在搜索字符串中_Php_Mysql_Laravel_Laravel 5_Eloquent - Fatal编程技术网

Php 使用Laravel eloquent搜索数据库列中的值是否出现在搜索字符串中

Php 使用Laravel eloquent搜索数据库列中的值是否出现在搜索字符串中,php,mysql,laravel,laravel-5,eloquent,Php,Mysql,Laravel,Laravel 5,Eloquent,我目前正在从事一个Laravel5.4项目,试图在我的数据库中找到类似于搜索字符串的值。例如,我有以下搜索词 $search\u term=“一些带单词的长短语” 在我的数据库(MySQL)中,我有一个表tags,其中有一个列value。此表中的一行可能有值=>'some',另一行可能有值=>'long',另一行可能有值=>'phra' 我需要的是创建一个所有标签的集合,其中值出现在我的搜索词中。这意味着我提到的3行应该与我的$search\u term 我现在知道我可以在拉雷维尔用雄辩的语言说

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

$search\u term=“一些带单词的长短语”

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

我需要的是创建一个所有标签的集合,其中
值出现在我的搜索词中。这意味着我提到的3行应该与我的
$search\u term

我现在知道我可以在拉雷维尔用雄辩的语言说

Tag::where('value','like',“%.”$search\u term.“%”->get()

但据我所知,这将看到
$search\u term
是否是
列中内容的子字符串


如何使用eloquent询问
$search\u term
中是否包含
value
子字符串?

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

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

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

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

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

使用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_替换('/\W+/','.$search_术语)
将用一个空格替换任何非单词字符序列。

我更喜欢这样,因为不是每个字符串都是有效的regexp

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

使用PHP将搜索词拆分为单个单词数组。然后使用
->,其中('tag',$words)
。你是说REGEXP是一个关键字还是我需要在这里输入正则表达式?
REGEXP
是一个关键字/运算符,就像是一样。
可怕的搜索词'REGEXP'car'
将返回TRUE。我的问题是,我不能保证数据库中的值是一个单词。出于上下文的考虑,该值可能是一个短语而不仅仅是一个单词。。。