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 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测