Laravel/Lumen api 过滤器
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'));
}
最近我正在尝试让我的 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'));
}