简体   繁体   English

使用全文搜索以通过laravel查询构建器查找部分单词

[英]Using Full-Text-Search in order to find partial words by laravel query builder

I would like to write search query that uses supplied phrase to search a table, return the value that matches any part of the phrase. 我想编写使用提供的短语搜索表的搜索查询,返回与短语的任何部分匹配的值。 this code is working, but results are nothing. 此代码有效,但结果一无所获。 For example, table have 'abcde', and I searched 'bcd', result is nothing. 例如,表中有“ abcde”,而我搜索了“ bcd”,结果为空。

protected function fullTextWildcards($term)
{
    return str_replace(' ', '*', $term) . '*';
}

public function index(Request $request, $slug = null)
{
    $query = $slug
        ? \App\Tag::whereSlug($slug)->firstOrFail()->articles()
        : new \App\Article;
    if ($keyword = request()->input('q')) {
        $raw = 'MATCH(title,content) AGAINST(? IN BOOLEAN MODE)';
        $query = $query->whereRaw($raw, [$this->fullTextWildcards($keyword)]);
    }

    $articles=$query->latest()->paginate(10);
    return view('articles.index',compact('articles'));
}

How to chain everything together so I achieve the desired result? 如何将所有内容链接在一起,以便达到预期的效果?
Thanks in advance. 提前致谢。

You can just use like in your query to get any matches in a given column. 您可以在查询中使用like来获取给定列中的所有匹配项。 Try this: 尝试这个:

public function index(Request $request, $slug = null)
{
  $filter = ['keyword' => $request->q , 'slug' => $slug];

  $articles = \App\Tag::where(function ($q) use ($filter){

    //you can leave this I just put the so the code seems clean
    if ($filter['slug'] !== null) {
      $q->whereSlug($slug);
    }

    if ($filter['keyword']) {

      $keyword  = $this->fullTextWildcards($filter['keyword']);

      //you can use **like** this
      $q->where('title', 'like', "%".$keyword."%")->orWhere('content', 'like',  "%".$keyword."%");
    }

  })->latest()->paginate(10);


  return view('articles.index',compact('articles'));

}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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