首页 > 解决方案 > 用作范围时,Laravel 查询不起作用

问题描述

我正在尝试按时间间隔查找记录。在表中有像'date_from'和'date_to'这样的列,它们指定事件的开始和结束日期。

public function scopeByTimeInterval($query, $dateInterval)
{
    $query->where(function ($query) use ($dateInterval) {
        [$from, $to] = $dateInterval;
        $query->where([
            ['date_from', '<=', $from],
            ['date_to', '>=', $to]
        ]);
        $query->orWhere([
            ['date_from', '>=', $from],
            ['date_to', '<=', $to]
        ]);
        $query->orWhereBetween('date_from', $dateInterval);
        $query->orWhereBetween('date_to', $dateInterval);
    });
}

当我where直接使用查询时,没有问题。我可以看到这些日期之间的所有事件。但是,如果我将它用作范围,它会返回给定年份和月份的每个事件,而不是间隔..

什么可能导致什么样的行为?还是我错过了什么?

标签: phplaravellaravel-5eloquent

解决方案


如评论中所述,您的查询本质上是选择所有内容。如果您试图获取在日期$from$to日期期间发生的事件,您可以执行以下操作:

public function scopeDateInterval($query, $interval)
{
    [$from, $to] = $interval;

    $query
        ->where(function ($query) use ($from, $to) {
            $query
                ->where(function ($query) use ($from) {
                    $query
                        ->where('date_from', '<=', $from)
                        ->where('date_to', '>=', $from);
                })
                ->orWhere(function ($query) use ($to) {
                    $query
                        ->where('date_from', '<=', $to)
                        ->where('date_to', '>=', $to);
                })
                ->orWhere(function ($query) use ($from, $to) {
                    $query
                        ->where('date_from', '>=', $from)
                        ->where('date_to', '<=', $to);
                });

        });
}

上面基本上是说$fromor$to在开始和结束日期之间的位置,或者开始和结束日期在$fromand之间$to


推荐阅读