简体   繁体   中英

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. 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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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