dongsheng8158 2016-04-02 17:30
浏览 25
已采纳

如何在Laravel 4查询构建器中使用文字问号

I'm writing a scope for a post resource with a text column to find posts containing a keyword. They keyword should match only if there is a space before and a space or typical punctuation mark afterward (.?!;,-)

Here's my scope method:

public function scopeContainsKeyword($query, $keyword) {
  return $query->where('post', 'LIKE', '% '.$keyword.' %')
               ->orWhere('post', 'LIKE', '% '.$keyword.'.%')
               ->orWhere('post', 'LIKE', '% '.$keyword.'!%')
               ->orWhere('post', 'LIKE', '% '.$keyword.';%')
               ->orWhere('post', 'LIKE', '% '.$keyword.',%')
               ->orWhere('post', 'LIKE', '% '.$keyword.'-%')
               ->orWhere('post', 'LIKE', '% '.$keyword.'?%');
}

This works perfectly if I comment out the orWhere with the question mark. However when that question mark is present, it is getting replaced with the value of the next parameter in the query (date values being checked with another scope), and the final parameter of the query isn't replaced and remains a question mark.

How do I escape this question mark to mark it as a literal question mark instead of a placeholder?

Things I've tried:

->orWhere('post', 'LIKE', DB::raw('\'% '.$keyword.'?%\''))

->orWhere('post', 'LIKE', '% '.$keyword.DB::raw('?').'%')

->orWhere(DB::raw('post LIKE \'% '.$keyword.'?%\'')

->orWhere('post', 'LIKE', '% '.$keyword.'\?%')

Nothing has worked. How do I get this to work?!

  • 写回答

1条回答 默认 最新

  • doujiu9172 2016-04-05 15:36
    关注

    From everything I've tried and a few others have tried helping me with, it seems like the question mark will always get replaced in the LIKE, however it does not get replaced in a REGEXP so this works (and is probably faster than the separate LIKE searches anyway):

    public function scopeContainsKeyword($query, $keyword) {
      return $query->where('post', 'REGEXP', ' '.$keyword.'[ ?!,;\-\.\'"]');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?