简体   繁体   English

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

[英]How can I use a literal question mark in Laravel 4 query builder

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. 如果我用问号orWhere ,这将非常有效。 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?! 我该如何工作?!

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): 从我尝试过的所有内容以及其他一些人尝试提供的帮助来看,好像问号将始终在LIKE被替换,但是在REGEXP它不会被替换,因此,它可以工作(并且可能比单独的要快)无论如何都LIKE搜索):

public function scopeContainsKeyword($query, $keyword) {
  return $query->where('post', 'REGEXP', ' '.$keyword.'[ ?!,;\-\.\'"]');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM