【问题标题】:Ignore apostrophes when querying database - Laravel 5.4查询数据库时忽略撇号 - Laravel 5.4
【发布时间】:2017-08-14 20:10:00
【问题描述】:

我的网站上有一个带有自动填充功能的搜索栏,用户可以在其中搜索旅行指南。 一些旅行指南的名称例如:Snookie's Outfitter 如您所见,它的名称中有一个撇号。因此,当用户输入第一个单词并点击该撇号时,查询会忽略其余部分,因为用户没有在搜索栏中插入撇号。我想知道我怎么可能忽略数据库中的撇号。

当有人搜索时,我的查询是这样设置的:

public function index()
    {
        $query = request()->get('query');

        $results = Listing::searchAndCache($query);

        return view('search.index', compact('results', 'query'));
    }

我的列表模型:

  public static function searchAndCache($query)
    {
        return self::whereHas('locations', function($m) use($query) {
            $m->where('region', 'like', '%'.$query.'%');
            $m->orWhere('country', 'like', '%'.$query.'%');
            $m->orWhere('city', 'like', '%'.$query.'%');
            $m->orWhere('county', 'like', '%'.$query.'%');
            $m->orWhere('regionCode', 'like', '%'.$query.'%');
        })->live()->orWhere(function($m) use($query){
            $m->where('name','like','%'.$query.'%');
            $m->live();
        })->paginate();
    }

我知道以前有人问过这个问题,特别是对于 PHP,但我只是不知道如何在 Laravel 搜索查询中实现它。

【问题讨论】:

  • 只需使用 HTML::entities() 对查询进行编码,这也是一种更安全的方法来保护您的查询免受注入。
  • 你知道如何用 SQL 来做吗?我非常擅长将 SQL 转换为 Laravel 语法。我不太擅长 SQL。
  • 我在这个链接上找到了一些东西,但他们使用的是常规的 php 语法:*.com/questions/4351337/…
  • @guyfawkes,我究竟会在哪里使用它,围绕输入?或在我收到请求的函数内部
  • 它应该在 return self::whereHas... 部分之前。在下面添加完整代码作为答案

标签: php mysql laravel laravel-5.4 querying


【解决方案1】:

您需要使用 HTML::entities() 对您的查询 sq 引号进行编码,双引号将被替换为 html 引用。

public static function searchAndCache($query)
{
    $query = HTML::entities($query);

    return self::whereHas('locations', function($m) use($query) {
        $m->where('region', 'like', '%'.$query.'%');
        $m->orWhere('country', 'like', '%'.$query.'%');
        $m->orWhere('city', 'like', '%'.$query.'%');
        $m->orWhere('county', 'like', '%'.$query.'%');
        $m->orWhere('regionCode', 'like', '%'.$query.'%');
    })->live()->orWhere(function($m) use($query){
        $m->where('name','like','%'.$query.'%');
        $m->live();
    })->paginate();
}

【讨论】: