首页 > 解决方案 > 使用布尔函数来确定 Laravel 查询生成器中的结果

问题描述

我有在特定时间打开并在特定时间关闭的商店,我想根据用户指定的时间段过滤这些商店,以便所有返回的商店在过滤间隔内的任何时刻都可用(打开)

商店晚上10点开门,下午2点关门,我的意思是商店晚上10点开门,第二天下午2点关门

我认为这是正确地完成工作

/*
    @param filterStart the beginning of the time period selected by the user in minutes from 00:00.
    @param filterEnd the end of the time period selected by the user in minutes from 00:00.
    @param start the beginning of the period of availability of the shop in minutes from 00:00.
    @param end the end of the period of availability of the shop in minutes from 00:00.
*/
bool ok(int filterStart, int filterEnd , int start, int end) {
    if (filterStart > filterEnd) 
        filterEnd += 24 * 60;

    if (start > end) 
        end += 24 * 60;

    if (start <= filterStart && filterEnd <= end)
        return true;

    if ((start <= (filterStart + 24 * 60)) && ((filterEnd + 24 * 60) <= end))
        return true;

    return false;
}

我在一个范围内(0 到 48 小时)合并了这两天,并测试了第一天开门的商店还是第二天开门的商店(第一天 + 24 小时)

但我想使用这个函数来使用 Laravel 从数据库中获取记录。

我可以在查询生成器的 WHERE 语句中传递一些函数来决定它吗?或者是什么方法?

标签: phpsqllaravel

解决方案


在您上次发表评论后编辑了我的答案。

假设您可以用 PHP 编写 C++ 函数。

function ok(int $filterStart, int $filterEnd , int $start, int $end): bool {
    if ($filterStart > $filterEnd) 
        $filterEnd += 24 * 60;

    if ($start > $end) 
        $end += 24 * 60;

    if ($start <= $filterStart && $filterEnd <= $end)
        return true;

    if (($start <= ($filterStart + 24 * 60)) && (($filterEnd + 24 * 60) <= $end))
        return true;

    return false;
}
// User inputs. I wrote 'X' because I don't know enough of your app.
$filterStart = X;
$filterEnd = X;

// Gets all elements of the table 'items'
$items->table('items')
    ->all()

    // Or you can already filters rows with 'where()' in place of 'all()' if you think it is better:
    // ->where('start_time', '>=', $filterStart)
    // ->where('end_time', '<=', $filterEnd)
    // ->get()

    // Do for each elements...
    ->each(function($item, $i) {
        $isOk = ok($filterStart, $filterEnd, $item->start_time, $item->end_time);

        if ($isOk) {
            // Operations to execute if return value is TRUE
        } else {
            // Operations to execute if return value is FALSE
        }
    });

我希望它至少可以帮助你一点!


推荐阅读