[英]Laravel/Lumen api filter
最近,我正在嘗試使我的api過濾工作。 我需要這樣過濾我的產品: http://localhost/search?feature_id=1,2,3,4,5...
如果我只發送1個ID,一切都很好。 但是如何使其以這種方式工作?
這是我的控制器:
public function search2(\Illuminate\Http\Request $request) {
$query = DB::table('tlt_product_features');
if ($request->has('feature_id') ) {
$query = $query->whereIn('feature_id', [$request->get('feature_id')]);
}
$products = $query->get();
return response()->json([
'products' =>$products
]);
}
使用explode()創建id
數組。
$ids = explode(",",$request->get('feature_id'));
$query = $query->whereIn('feature_id', $ids);
要在Laravel / Lumen一側開箱即用,必須以這種方式發送陣列:
http://localhost/search?feature_id[]=1&feature_id[]=2&feature_id[]=3...
在像PHP這樣的弱類型語言中,[]實際上被用作內部變通方法,以便能夠獲取多值參數。 您還可以指定一個索引:
http://localhost/search?feature_id[0]=1&feature_id[1]=2&feature_id[2]=3...
然后,您可以在控制器中使用:
if ($request->filled('feature_id')) {
// You could also check that you have a php array : && is_array($request->input('feature_id'))
// And that it's not an empty array : && count($request->input('feature_id'))
$query = $query->whereIn('feature_id', $request->input('feature_id'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.