whereBetween和orWhere获取日期范围内的数据

时间:2018-05-11 06:50:05

标签: php mysql laravel

我想得到日期范围created_at这里是我的示例表

id    status  created_at
1      1      2018-05-10 10:53:54
2      2      2018-05-10 10:53:54
3      2      2018-05-9 11:53:54

在我的控制器中

$this->to = 2018-05-10;
$this->from = 2018-05-09;
Table::whereBetween('created_at', [$this->from, $this->to]) 
                            ->orwhere('created_at', 'like', '%' .$this->to. '%')
                            ->where('status', 2); 

在此查询中,它会打印状态为1和2的所有数据,如何才能获得status2

我尝试die_dump我的sql我得到了这样的查询

select * from `table` where `created_at` between '2018-05-09' and '2018-05-10' or `created_at` like '%2018-05-10%' and `status` = '2'

2 个答案:

答案 0 :(得分:3)

您可以尝试whereBetween('created_at', [$this->from, $this->to])->orwhere('created_at', 'like', '%' .$this->to. '%')

的子查询
$from = $this->from;
$to = $this->to;
Table::where('status', 2)
            ->where(function ($query) use ($from,$to) {
                    $query->whereBetween('created_at', [$from, $to])
                                ->orwhere('created_at', 'like', '%' .$to. '%');
            });

答案 1 :(得分:1)

 Table::where(function($q) use ($from,$to)){
      $q->whereBetween('created_at', [$from, $to])
        ->orwhere('created_at', 'like', '%' .$to. '%')
    }->where('status', 2);

您可以搜索“嵌套/子查询eloquent laravel”以获取更多信息