我看到一些 API 具有可以在 url 中构造的简单查询。例如,我有带有产品模型的产品表。
产品表属性:
- 编号
- 产品名称
- 条形码
- 类别编号
- 描述
- 价格
如何在url中查询如下(fields参数表示选择那些指定的字段):
http://example.com/product?fields=id,product_name,price,barcode&sortby=price
或者可能像这样使价格等于 10.00:
http://example.com/product?fields=id,product_name,price,barcode&price=10.00
我知道在 laravel 中我们可以使用 $request->has()
检查获取参数并使用 $request->input('fieldname)
获取值到一个一个地检查和检索值
但我认为应该有更好的方法来做到这一点,或者也许有一个包装函数可用于所有 Controller 从 url get 参数读取查询。
谢谢
最佳答案
好的,我们开始吧。我会尽量说教。
待办事项
构建一个 API,根据 URL 参数从数据库中搜索和返回产品。
属性
首先,我们设置一个包含所有有效属性的数组。
$props = [
'id',
'product_name',
'barcode',
'category_id',
'description',
'price'
];
参数
让我们将所有来自 URL 的参数存储在一个变量中:
$parameters = Input::all();
无参数
如果传递了任何参数,我们可以选择所有产品及其字段并返回结果:
if (empty($parameters)) {
$products = Product::all();
return $products;
}
组织事物
假设我们有 3 个“类别”的参数:
- 确定要选择的字段(可选)。
- 确定结果顺序(可选)。
- 确定搜索子句(可选)。
识别字段
对于第一类,我们将使用 fields
参数,该参数接收一个用逗号分隔每个字段的字符串。
$fieldsParam = $parameters['fields']; // Gets fields string.
$fieldsParamSplit = explode(',', $fieldsParam); // Split the fields string into array.
$fields = array_intersect($props, $fieldsParamSplit); // Gets only wanted fields.
顺序
对于第二类,我们将使用接收特定字段(属性)名称的 sortby
参数。
$orderProp = null;
// Check if parameter "sortby" exists and if it is valid.
if (isset($parameters['sortby']) && in_array($parameters['sortby'], $props)) {
$orderProp = $parameters['sortby'];
}
有从句吗?
对于第三类,我们将使用所有参数(上述参数除外)来构建搜索的where 子句。
$clauses = [];
foreach ($props as $prop) {
// Check if the current property is present in parameters.
if (in_array($prop, array_keys($parameters))) {
// Each item represents a where clause.
$clauses[$prop] = $parameters[$prop];
}
}
构建集合
现在所有参数都已验证,我们可以构建产品集合并返回结果。
if ($orderProp) {
$products = Product::where($clauses)->orderBy($orderProp)->get($fields);
} else {
$products = Product::where($clauses)->get($fields);
}
return $products;
关于php - Laravel 5.2 使用 url get 参数创建查询以选择字段、匹配字符串和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470862/