Mysql Laravel 查询以逗号分隔的字符串是否包含某值或某些值
例子1:单词查询
8,9,10,12,13 需要查找 12
Mysql 查询
SELECT * FROM table where FIND_IN_SET(12, searchField)
Laravel 查询
// 如果值为字符串时,需要在查询语句中加上 ''
$searchValue = '12';
$searchField = 'items';
$this->model->whereRaw("FIND_IN_SET('" . $searchValue ."'," . $searchField . ")")->first();
例子2:多词查询
8,9,10,12,13 需要查找 8,9,12
Mysql 查询
SELECT * FROM table where searchField REGEXP "((^|,)(8,9,10)(,|$)"
Laravel 查询
public function getRegexpRules(){
$data = [8,9,12]
$str = '(^|,)(';
foreach ($data as $v){
$str = $str . $v . '|';
}
return substr($str,0,-1) . ')(,|$)';
}
$regexpRules = $this->getRegexpRules();
$searchField = 'items';
$this->mode->whereRaw($searchField . " NOT REGEXP '" . $regexpRules ."'")->first();