【问题标题】:Using Full-Text-Search in order to find partial words by laravel query builder使用全文搜索以通过 laravel 查询构建器查找部分单词
【发布时间】:2018-11-22 12:55:39
【问题描述】:

我想编写使用提供的短语来搜索表的搜索查询,返回与短语的任何部分匹配的值。 此代码有效,但结果一无所获。比如table有'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'));
}

如何将所有内容链接在一起以达到预期的效果?
提前致谢。

【问题讨论】:

    标签: php sql laravel query-builder


    【解决方案1】:

    您可以在查询中使用like 来获取给定列中的任何匹配项。试试这个:

    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'));
    
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 2014-06-29
      • 2011-02-27
      • 2016-07-10
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多