使用布尔函数在Laravel查询构建器中确定结果

时间:2019-03-04 07:59:25

标签: php sql 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语句中传递某个函数来确定它吗?还是可以用什么方法呢?

1 个答案:

答案 0 :(得分:0)

在您最后一次评论后编辑了我的答案。

假设您可以用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
        }
    });

我希望至少能对您有所帮助!