【发布时间】:2020-06-08 22:49:55
【问题描述】:
我正在尝试使用 Laravel 的 ORM Eloquent 查询 MySQL 表(我猜有点不相关)。我在表中有一个名为 quantitative 的字段,其中包含格式为 JSON
[{name: 'a', value: 3}, {name: 'b', value: 4}]。
我希望用户能够查询包含他以任何顺序指定的值的所有条目。
AllowedFilter::callback('quantitative', function (Builder $query, $value) {
$quantitative = collect($value)->filter(function ($el) {
return isset($el['value']);
})->pluck('value')->map(function ($el) {
return "(?=.*{$el})";
})->implode('');
$query->where('quantitative', 'regexp', "({$quantitative}).*");
}),
使用正则表达式(?=.*a)(?=.*b).*生成查询(如下)
SELECT count(*) as aggregate from `table` where `quantitative` regexp ((?=.*a)(?=.*b)).* (...)
它会产生以下错误:
SQLSTATE[42000]:语法错误或访问冲突:1139 从正则表达式中得到错误“重复操作符操作数无效”
当我在 regex101.com 上验证它时,Regex 本身工作得很好,我遇到的问题是它对 MySQL 语法无效。有没有办法让它工作或使用不同的正则表达式来完成任务?
【问题讨论】:
-
如果 MySQL 不是 v.8+,则不能在模式中使用前瞻。
-
只需使用
LIKE构建查询:SELECT count(*) as aggregate from table where quantitative LIKE "%a%" AND where quantitative LIKE "%b%"....
标签: mysql regex laravel eloquent