[英]Lumen API fancy filtering
how can I make a fancy filtering in Lumen API using query builder? 如何使用查询生成器在Lumen API中进行精美过滤? For example I would like to filter my products like this: http://localhost:8000/products?product_group=network
例如,我想这样过滤我的产品: http://localhost:8000/products?product_group=network
This is my controller: 这是我的控制器:
public function index(){
$tlt_product_groups = DB::table('tlt_products')->groupBy('product_group')->get()->toArray();
$tlt_products = DB::table('tlt_products')->get()->groupBy('product_group')->toArray();
return response()->json([
'categories'=> $tlt_product_groups,
'products' =>$tlt_products
]);
}
And this is my route: 这是我的路线:
$router->get('products','ProductController@index');
Before you don't call get()
on the query, it is still a query object and can be transformed further. 在不对查询调用get()
之前,它仍然是查询对象,可以进行进一步转换。 You don't have to write the whole query in one piece. 您不必将整个查询写成一件。 Therefore you should be able to do something like: 因此,您应该可以执行以下操作:
public function index(\Illuminate\Http\Request $request) {
$query = DB::table('tlt_products');
if ($request->has('product_group')) {
$query = $query->where('product_group', $request->get('product_group'));
}
$products = $query->get();
return response()->json([
'categories'=> $tlt_product_groups,
'products' =>$tlt_products,
]);
}
If you want to extend your filtering, you can also allow filtering on multiple columns without having to write the code for each new column again: 如果要扩展过滤,还可以允许对多个列进行过滤,而不必再次为每个新列编写代码:
public function index(\Illuminate\Http\Request $request) {
$filterColumns = ['product_group', 'price', 'manufaturer'];
$query = DB::table('tlt_products');
foreach ($filterColumns as $column) {
if ($request->has($column)) {
$query = $query->where('product_group', $request->get($column));
}
}
$products = $query->get();
return response()->json([
'categories'=> $tlt_product_groups,
'products' =>$tlt_products,
]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.