【问题标题】:Laravel match multiple search wordsLaravel 匹配多个搜索词
【发布时间】:2018-06-07 12:44:14
【问题描述】:

我正在尝试修改使用 Laravel 的模板,我对这种语言非常陌生。我正在尝试过滤搜索结果以匹配所有搜索词。

例如用户搜索“红色”,搜索返回所有红色结果。用户搜索“卡车”,搜索返回所有卡车。但如果用户搜索“Red Trucks”,搜索会返回“red”搜索结果和“trucks”搜索结果。所以那里有红色的汽车和红色的自行车,还有黄色的卡车等……但我只想展示“红色卡车”。如果结果没有保存其中的一个标签,我不希望它显示。目前它只需要包含一个标签并显示出来。

我知道我需要修改“标签”的“where”和“orwhere”部分,并可能将它们更改为“=”,但我无法通过反复试验使其正常工作。

作为参考,上传的红色卡车照片将在 phpmyadmin 的标签字段中包含以下内容:red,lowered,s10,truck,gloss,custom,stripes

所以搜索“Red Truck”应该返回这张图片,并且不包括任何“red”“cars”。

搜索文本框有一个 name="q" 和 id="srch-term" 。搜索“Red Truck”会在浏览器中显示 /search?q=red+truck。

基本代码:

public function search($search, $timeframe = null)
{
    $extends = explode(' ', $search);
    $images = $this->posts($timeframe)->Where('tags', 'LIKE', '%' . $search . '%')
        ->whereNull('deleted_at')->whereNotNull('approved_at')->orderBy('approved_at', 'desc');

    foreach ($extends as $extend) {
            $images->orWhere('tags', 'LIKE', '%' . $extend . '%')->whereNotNull('approved_at')->whereNull('deleted_at');
    }

    return $images = $images->with('user', 'comments', 'favorites')->whereNotNull('approved_at')->whereNull('deleted_at')->paginate(perPage());
}

【问题讨论】:

  • 您是否尝试将orwhere 替换为where 子句,结果如何
  • 单词搜索有效,但多词搜索返回 0 个结果。
  • 答案已更新。试试这种方式

标签: php laravel search laravel-5 eloquent


【解决方案1】:

想通了!

Public function search($search, $timeframe = null)
{
$extends = explode(' ', $search);
$images = $this->posts($timeframe)
             ->whereNull('deleted_at')->whereNotNull('approved_at') 
             ->orderBy('approved_at', 'desc');

$images->where(function($q) use ($extends) {
   foreach ($extends as $extend) {
       $q->Where('tags', 'LIKE', '%' . $extend . '%');
   }
});

return $images->with('user', 'comments', 'favorites')->paginate(perPage());
}

【讨论】:

    【解决方案2】:

    你做得很好。只需像这样在查询中使用whereIn

    $images->whereCategoryId($categoryId)->whereIn('tags', $extends)->whereNotNull('approved_at')->whereNull('deleted_at');
    

    更新答案

    public function search($search, $category = null, $timeframe = null)
    {
        if ($category)
            $categoryId = $this->category->whereSlug($category)->first();
    
        $images = $this->posts($category, $timeframe)->with('user', 'comments', 'favorites')->whereNotNull('approved_at')->whereNull('deleted_at');
    
        if (isset($categoryId))
            $images->whereCategoryId($categoryId);
    
        $images->whereIn('tags', explode(' ', $search));
    
        return $images->orderBy('approved_at', 'desc')->paginate(perPage());
    }
    

    【讨论】:

    • 现在所有搜索都返回空白/空。我已经调整了我最初的代码 sn-p 以删除类别提及,因为无论如何我都想搜索所有类别。'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多