问题
What's the best way to use Fluent or Eloquent to search for a pattern in a MySQL database and replace it?
I've seen in the Laravel forums that you should be able to do a regex selection like so
// Searching for the word "mypattern"...
Page::where('words', 'regexp', DB::raw('/\bmypattern\b/'))->get();
But I've tried this method and it doesn't seem to select the rows I'm after. In any case, actually don't want to JUST select--I'd like to actually do a search and replace with regex.
What's the best way to do this with the options provided by Laravel?
回答1:
I don't believe that 'regexp' is a valid query operator in Laravel 4.
It seems that Taylor has actually made a comment specific to this issue on Github under issue #838, and he suggests using whereRaw instead of where.
Here is an SO question regarding MySQL Regex Replace, which may help you to implement this.
回答2:
You could possibly use a MySQL User Defined Function
(UDF) for what you're asking. Note that using a UDF
is not always compatible but might be good enough to do for your case.
The UDF package mod will implement your regular expression as a User Defined Function and is supported by the regular expression REGEXP
operator.
See MySQL regular expression functions
Another option would be to dump your data and do a find and replace.
来源:https://stackoverflow.com/questions/18884333/regex-search-and-replace-on-all-rows-in-a-table-with-laravel-4s-fluent-or-eloqu