简体   繁体   English

Laravel:按相似字符串搜索

[英]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 .用户很可能会打错字,所以我希望能够找到产品是用户键入的corruptacorrupi而不是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

  1. use metaphone (or soundex) to encode words you want to be searchable使用 metaphone(或 soundex)对您想要搜索的单词进行编码
  2. put them in a database column say products.name_as_metaphone把它们放在数据库列中说 products.name_as_metaphone
  3. make your search function encode searched word to metaphone, then make it look in the metaphone column (and not in product.name)...让您的搜索 function 将搜索到的单词编码为 metaphone,然后让它在 metaphone 列中(而不是在 product.name 中)...
  4. profit利润

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM