【问题标题】:Search function Laravel 5.8 not working for plural words搜索功能 Laravel 5.8 不适用于复数词
【发布时间】:2019-04-26 11:36:29
【问题描述】:

我的应用程序中目前有一个搜索功能,它工作得很好,但我希望它返回更广泛的搜索。让我解释。

我有一个食谱应用程序,每个用户都可以在其中上传食谱。在搜索栏中,您可以搜索食谱并根据数据库中的内容返回结果。我的问题是,如果您搜索复数形式的内容,或者拼写错误,则没有输出。示例:当食谱标题为冰沙(单数)时,搜索冰沙(复数)。但是,如果您搜索食谱并且单词不完整(smooth、smo、sm),则它会返回包含完整单词的所有结果。所以我想要同样的功能,但是对于有太多字母或复数形式的单词。

这是我目前的逻辑:


public function search(Request $request){
        $q = $request->input('search');
        $recipes = Recipe::where('title', 'LIKE', '%'.$q.'%')->orWhere('description', 'LIKE', '%'.$q.'%')->get();
        return view('recipes.results')->with('recipes', $recipes)->with('query', $q);


该功能搜索食谱的标题和描述。

感谢我能得到的任何帮助!

【问题讨论】:

  • 对于我认为的复数词 ('title', 'LIKE', $q.'%') 会起作用,但对于拼写错误搜索,我认为你需要查看 laravel scout 和像 algolia 这样的驱动程序/ 弹性搜索 / 或者像 TNT 搜索侦察驱动这样的免费驱动

标签: php laravel eloquent


【解决方案1】:

让我改写你的代码。并尝试阅读 laravelLaravel Helpers 这个有用的助手

use Illuminate\Support\Str;
//dont forget to import this


public function search(Request $request){

    $q = $request->input('search');
    $singular = Str::singular($q);
    $plural= Str::plural($q);

    $recipes = Recipe::where('title', 'LIKE', '%'.$singular .'%')
       ->orWhere('title', 'LIKE', '%'.$plural.'%')
       ->orWhere('description', 'LIKE', '%'.$singular .'%')
       ->orWhere('description', 'LIKE', '%'.$plural.'%')
       ->get();

    return view('recipes.results')->with('recipes', $recipes)->with('query', $q);

【讨论】:

  • 拼错的怎么办?
【解决方案2】:

这会起作用,但我认为这不是正确的方法

public function search(Request $request){
    $q = $request->input('search');
    $recipes = Recipe::where(function($query) use($q){
        for($x = 3; $x < strlen($q); $x++) {
            if($x==3) {
                $query->where('title', 'LIKE', '%'.substr($q, 0, $x).'%');
            }
            else {
                $query->orWhere('title', 'LIKE', '%'.substr($q, 0, $x).'%');
            }
        }
    })->orWhere('description', 'LIKE', '%'.$q.'%')->get();
    return view('recipes.results')->with('recipes', $recipes)->with('query', $q);

当用户搜索“冰沙”时,它会搜索所有的食谱

smo、smoo、smoot、smooth、smoothi、smoothie、smoothies

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2015-10-04
    • 2018-08-06
    • 2019-03-08
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多