【问题标题】:How to do a mysql affinity query with various terms taken from an array in laravel如何使用从 laravel 中的数组中获取的各种术语进行 mysql 关联查询
【发布时间】:2020-12-23 06:06:20
【问题描述】:

我有一个索引有 16 个术语的数组,我需要 mysql 来查找与这 16 个术语或其中至少一个术语相关或对应的文章。

在 laravel 中没有“IN”,有“whereIn”,他只接受一个字符串,我无法创建一个包含 16 个术语的字符串,因为他不识别逗号,我使用的是 php 7.4并且容忍度似乎更低。我试图用implode()将数组转换成字符串,但它不起作用,它返回一个“将数组转换为字符串”错误,查看文档我发现了一些与集合相关的东西,但是,它不接受,它确实必须是一个字符串。我尝试使用 orWhere ,虽然它不返回错误,但它不显示结果并且需要很长时间来处理。 该数组是标准模型中的索引数组:

数组(['1', '2', '3' ...]);

除了条款,我还需要检查文章是否来自当前用户,这是有效的,记住数组及其内容是固定的,在控制器中。

  $link = (['title', 'category', 'description', 'body', 'jobs', 'colors', 'phone', 'about', 'shopping', 'trade', 'costumers', 'author', 'online', 'cloud', 'technology', 'company']);
            $linkt = My::where('id', $user->id)->whereIn($link);

    $linkt = My::where('id', $user->id)->whereIn('from', 'LIKE', '%' . $link);

$test = implode(",", $link);
$linkt = My::where('id', $user->id)->whereIn($test);

这些东西不适合我。

【问题讨论】:

  • Laravel whereIn 接受一个数组...例如:$users = DB::table('users') ->whereIn('id', [1, 2, 3]) ->get();
  • 我不能包括整个控制器,但我会把搜索功能和数组放在问题中
  • whereIn的第一个参数需要是列名。您要匹配的值的第二个参数数组。
  • ParseError 语法错误,意外',' (whereIn('from', $link);) 没用,你觉得把数组放在whereIn()里面比较好?跨度>
  • 即使把数组放在 whereIn() 里面也返回一个空数组 [],我有 10 个结果对应这些词,它们在一个文本中,在 from 列中,它们是不同的记录。

标签: php mysql arrays laravel eloquent


【解决方案1】:

既然您正在构建一个搜索查询,为什么不在遍历链接(搜索词)数组后构建查询?

类似这样的:

$link = (['title', 'category', 'description', 'body', 'jobs', 'colors', 'phone', 'about', 'shopping', 'trade', 'costumers', 'author', 'online', 'cloud', 'technology', 'company']);

$link = collect($link);

$query = My::where('id', $user->id)->where('from', 'like', '%'.$link[0].'%';

$link->shift(); // remove first element since it's used

$link->each(function($item) use ($query){
  $query->orWhere('from', 'LIKE', '%'.$item.'%'); //assuming that 'from' is your column name
} );

$query->get(); //to retrieve the results

另一种选择是使用whereRaw 发送通过内爆数组推导出的原始语句。像这样的:

$link = ([..]); //link array
$linkImploded = implode("%' OR '%", $link);
$finalLikeStatement = "from LIKE '%{$linkImploded}%'";

My::where('id', $user->id)->whereRaw($finalLikeStatement)->get(); 

【讨论】:

  • 谢谢,这可行,但我担心由于多个请求导致的循环会减慢应用程序的速度,我当然必须为此创建一个队列,我会在之前看到更多关于它的内容实施它。
  • 添加了另一个选项。但是,如果您担心性能,LIKE 可能不是您想要的方法。我建议查看全文搜索。
  • 我忘了问,每个学期只产生一个结果,我怎样才能把它们全部找回来?
  • get() 返回所有匹配项。如果您得到 1 个结果,则可能意味着有一个结果符合所有这些条件。为了确保,为什么不在 mysql 客户端中运行原始查询,看看它是否会产生更多结果?
  • 这一行给我报错,好像是mysql的版本不兼容,我正在找类似的东西可以测试。 -> $finalLikeStatement
猜你喜欢
  • 1970-01-01
  • 2016-06-27
  • 2013-10-07
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 2016-10-11
相关资源
最近更新 更多