雄辩的多个where from日期字段<= >=


Eloquent multiple where from date fields <= >=

我想从mySql表中选择Items
我用的是Laravel 5.2雄辩的

我的表结构:
Id | item_id | name | date_start | date_end

  • id = primary, auto
  • item_id = int
  • name = text
  • date_start,date_end为"日期"类型,格式为"2016-09-14"
我查询:

$dateFormated = date('Y-m-d',$tempDate);
$items = ItemList::where('item_id', $id)
  ->where('date_start', '>=', $dateFormated)
  ->where('date_end', '<=', $dateFormated)
  ->get()

如果我删除一个我的where 子句,我得到正确的结果所有项目具有正确的date_start/date_end值。

我做错了什么,我能做什么?

你只需要交换运算符就可以了

  ->where('date_start', '<=', $dateFormated)
                         ^
  ->where('date_end',   '>=', $dateFormated)
                         ^

根据注释中提供的数据,date_start必须落在之前或上,而formattedDatedate_end则落在之后,因此您的情况与应该的情况相反。


老回答

  ->where('date_start', '>=', $dateFormated)
  ->where('date_end', '<=', $dateFormated)

如何将开始日期和结束日期与同一日期进行比较,除非您只想查找一个特定日期的记录?

语法没问题,但逻辑可能不行。这样的查询将产生如下内容

WHERE date_start>="2016-09-13" and date_end<="2016-09-13"
你确定你在找那些唱片吗?

这就是为什么当你删除一个与日期相关的where子句时你会得到好的结果——这些事件不是在同一个日期开始和结束的。

在注释中确认,这实际上是的问题。WHERE条款不符合要求。解决方案是使用或where

帮我一把

    if($start_date!=''){
            $q->whereDate('date_start', '>=', date('Y-m-d', strtotime($start_date)));
    }
    if($end_date!=''){
            $q->whereDate('date_end', '<=', date('Y-m-d', strtotime($end_date)));
    }
试一试,希望能有所帮助。