[英]Laravel: Search by similar string
I'm trying to make a search feature on laravel. now I'm using this query:我正在尝试在 laravel 上创建搜索功能。现在我正在使用此查询:
$products = Product::with(['category', 'store'])
->when($keywords, function ($query) use ($keywords) {
$query->where('name', 'LIKE', '%' . $keywords . "%")
->orWhere('description', 'LIKE', '%' . $keywords . '%');
})->get()
The problem is, say on the database i've a product with the name corrupti
, If i searched by the exact name or removed a character from beginning or end it works fine, but if I changed a single character it returns an empty list.问题是,假设在数据库中我有一个名为
corrupti
的产品,如果我按确切名称搜索或从开头或结尾删除一个字符,它工作正常,但如果我更改单个字符,它返回一个空列表。
Users are likely to make typos, so I want to be able to find the product is the user typed corrupta
, corrupi
instead of corrupti
.用户很可能会打错字,所以我希望能够找到产品是用户键入的
corrupta
, corrupi
而不是corrupti
。
I know this is not a simple task to achive, I googled many things but I didn't find a solution.我知道这不是一项简单的任务,我用谷歌搜索了很多东西,但没有找到解决方案。
One thing I've came accross is the php similar_text
funciton, it may be useful but I didn't find a way to include it in the database query.我遇到的一件事是 php
similar_text
,它可能很有用,但我没有找到将它包含在数据库查询中的方法。
https://www.php.net/manual/en/function.soundex.php https://www.php.net/manual/en/function.metaphone.php https://www.php.net/manual/en/function.soundex.php https://www.php.net/manual/en/function.metaphone.php
try this:尝试这个:
$query = Product::query();
$searches = explode(' ', $request->query('q'));
if (isset($searches)) {
foreach ($searches as $search) {
$query->where(function ($q) use ($search) {
$q->where('code', 'ilike', '%' . $search . '%')
->orWhere('name', 'ilike', '%' . $search . '%');
});
}
}
$data = $query->get();
return ([
'success' => true,
'response' => $data,
'message' => 'Your message here'
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.