douliedu335997 2015-11-26 16:47
浏览 49
已采纳

Laravel 5.1:SQL查询'LIKE%word%word%word%'无效

Keep in mind I have minimal SQL experience, so I may be doing it all wrong.

I'm trying to set up search for a table but simply searching for the string a user enters is not ideal because though something may come up for "steve", if a user types "steve jobs story", nothing will match if that doesn't exist, as it'll be looking for that whole string instead of looking for each word respectively.

I tried to break it down by exploding the string into an array and then imploding that and separating it with %'s, so a search like "steve jobs story" would be "steve%jobs%story", and with my query it would be "%steve%jobs%story%". When I try searching this, I get no error but the query finds nothing, whereas when I just type one word it works, so I'm guessing what I'm trying to do isn't allowed.

Can someone point me in the right direction? Here is my controller/model:

// Controller

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

$explodedQuery = explode(" ", $query);
$newQuery = implode("%", $explodedQuery);

$articles = Article::isLikeTitle($newQuery)
                   ->isLikeBody($newQuery)
                   ->latest('published_at')
                   ->published()
                   ->paginate(10);

// Model

public function scopeIsLikeTitle($query, $q)
{
    return $query->where('title', 'LIKE', "%$q%");
}

public function scopeIsLikeBody($query, $q)
{
    return $query->where('body', 'LIKE', "%$q%");
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-11-26 17:17
    关注

    You can use loop to append the query with orWhere like this

    $query = $request->get('q');
    
    $explodedQuery = explode(" ", $query);
    
    $articles = Article::isLikeTitle($explodedQuery)
                       ->isLikeBody($explodedQuery)
                       ->latest('published_at')
                       ->published()
                       ->paginate(10);
    
    // Model
    
    public function scopeIsLikeTitle($query, $q)
    {
        foreach($q as $eachQueryString)
        {    
            $query->orWhere('title', 'LIKE', '%'.$eachQueryString .'%');
        }
        return $query;
    }
    
    public function scopeIsLikeBody($query, $q)
    {
        foreach($q as $eachQueryString)
        {    
            $query->orWhere('body', 'LIKE', '%'.$eachQueryString .'%');
        }
        return $query;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)