【问题标题】:Get A Collection of Data and Limit Them by Start and End Date获取数据集合并按开始和结束日期限制它们
【发布时间】:2020-04-23 15:07:00
【问题描述】:

我有根据 start_date 和 end_date 列保存数据的 SpecialPrice 模型,如下面的屏幕

我想要达到的目标如下:

  1. 如果用户选择从 2020-04-23 到 2020-04-26 的日期,我应该只检索第一个对象。
  2. 但如果用户选择从 2020-04-23 到 2020-04-27 的日期,我应该只检索第一个和第二个对象。
  3. 但如果用户选择从 2020-04-23 到 2020-05-01 的日期,我应该检索三个对象等。

在我的模型中,我有作用域函数,但我尝试过,但我知道它有问题

public function scopeBetweenDates($query,$start_date , $end_date){
    return $query->whereRaw('? between start_date and end_date', [$start_date])
                ->orWhereRaw('? between start_date and end_date', [$end_date]);
}

提前致谢

【问题讨论】:

    标签: php laravel eloquent scope


    【解决方案1】:

    这对我有用

    public function scopeWhereIntersectsStartDate($query,$start_date){
    
        return  $query->whereNotNull('start_date')
                      ->where('start_date' , '>' , $start_date)
                      ->orWhere('end_date' , '>' , $start_date);
    }
    
    public function scopeWhereIntersectsEndDate($query,$end_date){
    
        return  $query->whereNotNull('end_date')
                      ->where('end_date' , '<' , $end_date)
                      ->orWhere('start_date' , '<' , $end_date);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多