[英]Laravel query find comma separated and normal string
我有一个名为fac
的列,其值可以是单个数字,例如2
,也可以是逗号分隔,例如2,4,5
我想通过api
从数据库中获取数据。 值也可以是单个或逗号分隔。 所以用户可以像这样搜索:
localhost/api/search
{fac: 1}
或者
localhost/api/search
{fac: 1,4,5}
我使用find_in_set
但看起来在这种情况下它不起作用:
$fac = request('fac');
->whereRaw("find_in_set({$fac}, fac)")->get();
如果我运行这个localhost/api/search
{fac: 1}
它什么也不返回,如果我运行localhost/api/search
{fac: 1,4,5}
它给我错误:
语法错误或访问冲突:1582 调用本机 function 'find_in_set' 时参数计数不正确
目标:
如果用户搜索1
它应该返回所有包含1
的数据,如果搜索1,7
应该返回所有包含1
和7
的数据
首先,将逗号分隔的字符串转换为数组。 并创建原始查询。
$fac = request('fac'); // single value or comma saperated string
$data = explode(',',$fac);
$str='';
$i=1; // to append AND in query
foreach ($data as $key => $value) {
$str .= 'FIND_IN_SET("'.$value.'" ,fac)';
if($i < count($data)){
$str .=' AND '; // use OR as per use
}
$i++;
}
现在 $str 将包含原始查询
FIND_IN_SET("1", fac) AND FIND_IN_SET("7", fac)
您可以在 eloquent 中使用。
->whereRaw($str)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.