带有大量参数的可选查询

时间:2021-04-21 14:52:57

标签: laravel eloquent laravel-query-builder

我必须从我的商店商品中建立一个查询。我的商店物品有 10 个字段。我只是让客户在我的可选项目中搜索。 例如,第一个可能想要过滤 field1,第二个可能想要过滤 field1 和 field2,第三个可能想要过滤 field6 和 field8 以及 filde9,...。

我怎样才能使查询更短更有效?

注意 1:我不想使用 Raw 方法,因为它存在漏洞。

注意 2: 我在 link 1link 2 中看到一些答案,但我认为第一个不能用于 条件如:where('field1','>=','somevalue')where('field2','like','%somevalue%') 或任何类型的具有某种复杂性的条件,第二个条件有更多的“if”链接,如果可能的话,我希望比这更短

1 个答案:

答案 0 :(得分:1)

您可以通过多种方式执行此操作,具体取决于您喜欢的语法。一种可能的方法是使用分隔符号来传递多个参数:

/api/user?where[]=user_id|>=|5
/api/user?where[]=user_id|2
/api/user?where[]=user_id|2&where[]=status|activated

这只是允许您传递多个 where 选项,其中管道 | 运算符分隔参数。请注意,例如,如果您希望管道字符可用作搜索参数,这可能会导致问题。

然后您可以简单地将此网址解析为您的查询,如下所示:

foreach($request->get('where') as $i => $values) {
    $values = explode('|', $values);
    // Allow the third argument to be exchanged with the second one,
    // similar to how the Laravel `where()` method works.
    $query->where($values[0], $values[1], $values[2] ?? null);
}

或者,您可以添加验证方法,以便事先正确检查语法。您可以将此代码段添加到服务提供商的某些 boot() 方法中:

\Illuminate\Support\Facades\Validator::extend('query_where', function($attribute, $value) {
    // Require minimum length of 2 parameters.
    return count(explode('|', $value)) >= 2;
});

接下来,您在控制器操作中的验证将如下所示:

$this->validate($request, [
    'where' => 'nullable|array',
    'where.*' => 'query_where',
]);

可能性是无限的。

相关问题