【问题标题】:Laravel/Lumen api filterLaravel/流明 api 过滤器
【发布时间】:2018-09-12 12:09:32
【问题描述】:

最近我正在尝试让我的 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
        ]);
    } 

【问题讨论】:

    标签: php laravel api lumen


    【解决方案1】:

    使用explode() 制作id 的数组。

    $ids = explode(",",$request->get('feature_id'));
    $query = $query->whereIn('feature_id', $ids);
    

    【讨论】:

    • 哦,它有效.. 我很确定我以前做过,但它没有用 :D 谢谢 :)
    • 我不明白你,它是否有效?如果不起作用,则显示dd($ids) 在第一行之后给出的内容
    【解决方案2】:

    要在 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'));
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 2015-05-14
      • 2013-10-25
      • 2014-09-23
      • 2023-03-24
      • 2015-04-26
      相关资源
      最近更新 更多