[英]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.