【问题标题】:Laravel Eloquent Problem - can't search for single word [duplicate]Laravel Eloquent 问题 - 无法搜索单个单词 [重复]
【发布时间】:2021-05-16 06:41:09
【问题描述】:

您好,我正在尝试编写一个搜索功能,用关键字查找所有服务名称

$serviceids = Service::where('service_name', 'like', '%' . $key . '%')->pluck('service_recordid');

这是我现在所拥有的,但是当我搜索“租金”时,此结果也会返回“父母”,因为租金包括在内。我该怎么做才能使条件成为一个独特的词?

【问题讨论】:

标签: laravel


【解决方案1】:

您当前的搜索在搜索词前后使用%。通过这样做,您实际上添加了您不想要的行为 - 您搜索包含您的术语的任何内容。

$serviceids = Service::where('service_name', $key)->pluck('service_recordid');

一个简单的 where 没有 like 和 % 将返回任何 serviceId 与确切的键作为名称

编辑:如果您想确保与一个单词完全匹配,您可以使用多个 where 子句 (Match only entire words with LIKE?)

$serviceids = Service::where('service_name', 'like', '% ' . $key . ' %')
                       ->orWhere('service_name', 'like', '% ' . $key)
                       ->orWhere('service_name', 'like', $key . ' %')
                       ->orWhere('service_name', $key)
                       ->pluck('service_recordid');

空格是确保它直接适合的关键

【讨论】:

  • 有什么我可以用关键字来查找“此租金支付”,但不包括“父母”之类的东西?我认为给你的提示是搜索完全匹配的键。
  • 你可以加个空格吗? '% rent%'
  • 我已经相应地更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2016-05-20
  • 2020-01-22
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多