php url排序,php – Laravel 5.2使用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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值