使用全文搜索以通过 laravel 查询生成器查找部分单词
Using Full-Text-Search in order to find partial words by laravel query builder
我想编写使用提供的短语搜索 table、return 匹配短语任何部分的值的搜索查询。
这段代码有效,但结果一无所获。比如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'));
}
如何将所有内容链接在一起以达到预期的结果?
提前致谢。
您只需在查询中使用 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'));
}
希望对您有所帮助
我想编写使用提供的短语搜索 table、return 匹配短语任何部分的值的搜索查询。 这段代码有效,但结果一无所获。比如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'));
}
如何将所有内容链接在一起以达到预期的结果?
提前致谢。
您只需在查询中使用 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'));
}
希望对您有所帮助