Php Laravel 5.2使用url get参数创建查询,以选择字段、匹配字符串和排序
我见过一些API有简单的查询,可以在url中构造。例如,我有产品表和产品模型 产品表属性:Php Laravel 5.2使用url get参数创建查询,以选择字段、匹配字符串和排序,php,laravel,Php,Laravel,我见过一些API有简单的查询,可以在url中构造。例如,我有产品表和产品模型 产品表属性: 身份证 产品名称 条形码 类别识别码 描述 价格 如何在url中进行如下查询(fields参数表示选择指定的字段): http://example.com/product?fields=id,产品名称、价格、条形码和排序比=价格 或者像这样获得10.00美元的价格: http://example.com/product?fields=id,产品名称、价格、条形码和价格=10.00 我知道在larave
- 身份证
- 产品名称
- 条形码
- 类别识别码
- 描述
- 价格
http://example.com/product?fields=id,产品名称、价格、条形码和排序比=价格
或者像这样获得10.00美元的价格:
http://example.com/product?fields=id,产品名称、价格、条形码和价格=10.00
我知道在laravel中,我们可以使用$request->has()
检查get参数,并使用$request->input('fieldname)
逐个检查和检索值来获取值
但我认为应该有更好的方法来实现这一点,或者可能有一个包装器函数,可以用于所有控制器从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
参数
有一些条款吗? 对于第三类,我们将使用所有参数(上面提到的除外)来构建搜索的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;
非常好,先生。您还使用
array\u intersect
为字段添加了验证部分。没想到。除了最后一个代码外,我还可以工作,如果($orderProp)
我假设需要更改。谢谢sir@h44f33z哦,是的,当然此行还需要更改以在//中使用array\u键
//检查当前属性是否存在于参数中。
if(在数组($prop,array\u键($parameters))中)
。就这样。现在我想把它放在基本控制器上,这样它就可以重用了。谢谢
if ($orderProp) {
$products = Product::where($clauses)->orderBy($orderProp)->get($fields);
} else {
$products = Product::where($clauses)->get($fields);
}
return $products;