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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办