如何在laravel中搜索多个关键字? [英] how can i search multiple keywords in laravel .?

查看:461
本文介绍了如何在laravel中搜索多个关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的控制器

 $term = $request->get('q');

 // return $request->q;

 $products = Post::whereHas('user', function($query) use($term) {
     $query->where('name', 'like', '%'.$term.'%');
 })->orWhere('tags','LIKE','%'.$term.'%')->get();
 return view('pages.search', compact('products','users'));

这对于单个关键字搜索非常有效.但我想将其用于多个关键字.像laravel php等.当我搜索多个值(例如abc php laravel或其他任何值)时,请引导我,它应该可以工作.如果在我搜索php laravel时,标签存在于不同的列中,例如php位于第一列中,而laravel位于下一列中,则它应该显示两个列值.

This is working good for single keyword search. But I want to use it for multiple keywords. Like laravel php etc. Please guide me when I search multiple values like abc php laravel or anything then it should work. If tags exists in different column like php is present in 1st column and laravel is in next column when I search php laravel then it should show me both column values.

推荐答案

也许有更好的方法,例如使用CloudSearch/Algolia,但这是对我们有用的解决方案:

There is probably a better way to do this, like using CloudSearch/Algolia, but this is a solution that has worked for us:

// Split the terms by word.
$terms = explode(" ", request('q'));

$products = Post::query()
    ->whereHas('user', function ($query) use ($terms) {
        foreach ($terms as $term) {
            // Loop over the terms and do a search for each.
            $query->where('name', 'like', '%' . $term . '%');
        }
    })
    ->orWhere(function ($query) use ($terms) {
        foreach ($terms as $term) {
            $query->where('tags', 'like', '%' . $term . '%');
        }
    })
    ->get();

这篇关于如何在laravel中搜索多个关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆