laravel search multiple words separated by space

前端 未结 7 1982
鱼传尺愫
鱼传尺愫 2020-12-29 08:57

I am new to laravel query builder, I want to search multiple words entered in an input field for example if I type \"jhon doe\" I want to get any column that contains jhon o

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 09:37

    Have you considered using a FULLTEXT index on your first_name column?

    You can create this index using a Laravel migration, although you need to use an SQL statement:

    DB::statement('ALTER TABLE users ADD FULLTEXT(first_name);');
    

    You can then run quite advanced searches against this field, like this:

    $keywordRaw = "john doe";
    $keywords   = explode(' ', $keywordRaw);
    $users   = User::select("*")
                  ->whereRaw("MATCH (first_name)
                              against (? in boolean mode)",[$keywords])
                  ->get();
    

    That will match records containing either the words "john" or "doe"; note that this approach will match on whole words, rather than substrings (which can be the case if you use LIKE).

    If you want to find records containing all words, you should precede each keyword with a '+', like this:

    $keywords   = '+'.explode(' +', $keywordRaw);
    

    You can even sort by relevance, although this is probably overkill for your needs (and irrelevant for "all" searches). Something like this:

    $users = User::select("*")
                   ->selectRaw("MATCH (first_name)
                                against (? in boolean mode)
                                AS relevance",[$keywords])
                   ->whereRaw("MATCH (first_name)
                               against (? in boolean mode)",[$keywords])
                   ->orderBy('relevance','DESC')
                   ->get();
    

    There is a good article that covers this general approach here:

    http://www.hackingwithphp.com/9/3/18/advanced-text-searching-using-full-text-indexes

提交回复
热议问题