Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

多重条件判读查询,代码如何优化?

题目描述

在一个列表数据中,我们可能会有一些筛选条件,这些筛选条件是用户随机勾选的。后端需要根据这些筛选条件做数据查询,就会涉及到某个筛选字段存在,其他的筛选字段不存在的情况。如果用大量的 if 去判断,代码就不够优雅,该如何优化?

相关代码

这里就用 PHP 代码作为示例代码了,正好手里有 PHP 代码。

// 前端请求传入筛选参数
$requestParams = [];
// 根据传入的筛选参数组装筛选条件
$searchWhere = [];
if (!empty($requestParams['id'])) {
    array_push($searchWhere, ['id', '=', $requestParams['id']);
}
if (!empty($requestParams['name'])) {
    array_push($searchWhere, ['name', '=', $requestParams['name']);
}
if (!empty($requestParams['score'])) {
    array_push($searchWhere, ['score', '>', $requestParams['score']);
}
if (!empty($requestParams['dates'])) {
    $date = explode(',', $requestParams['dates']);
    array_push($searchWhere, ['date', '>', $date[0]);
    array_push($searchWhere, ['date', '<', $date[1]);
}
// 查询数据
$items = DB::query()->where($searchWhere)->get();

你期待的结果是什么?实际看到的错误信息又是什么?

能够减少 if 条件的判断。最好是能封装成一个类什么的,来进行处理。减少这种重复、低效的代码。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
个人看法,不代表所有人

1,你的代码从性能层面讲,是最快的
2,你的代码维护角度讲,是容易让人看懂的,能看懂每一个参数是做什么用的,什么判断条件
3,如果所有的条件都为空,你会不会查全表哦

所以我觉得,这个代码没有必要去优化,看起来优雅和真正的维护性相比,我选维护性,当然了,如果重复的地方比较多,那就另说了,个人意见
// 前端请求传入筛选参数
$requestParams = ['id' => 1, 'name' => 'test', 'score' => 10, 'dates' => '2020-11-01,2020-11-12'];

// 根据传入的筛选参数组装筛选条件
$searchWhere = [];

foreach ($requestParams as $key => $value) {
    if($row = format($key, $value, $condition)) {
        $searchWhere[] = $row;
    }
}

function format($key, $value, $condition)
{
    //有特殊情况,增加配置这里的逻辑就好了
    $condition = ['id' => '=', 'name' => '=', 'score' => '>', 'dates' => 'range'];
    if($condition[$key] == 'range') {
        $value = explode(',', $value);
        return ["between {$value[0]}", 'and', $value[1]];
    }

    return [$key, $condition[$key], $value];
}
Array
(
    [0] => Array
        (
            [0] => id
            [1] => =
            [2] => 1
        )

    [1] => Array
        (
            [0] => name
            [1] => =
            [2] => test
        )

    [2] => Array
        (
            [0] => score
            [1] => >
            [2] => 10
        )

    [3] => Array
        (
            [0] => between 2020-11-01
            [1] => and
            [2] => 2020-11-12
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...