wherebetween方法

7fhtutme  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(339)

我正试图以雄辩的格式编写以下查询:

SELECT * FROM `table_name` where timestamp_col1 AND timestamp_col2 BETWEEN 
'2018-07-23 11:45:25' and '2018-07-23 14:45:25'

通过使用eloquent的默认方法,我能够以以下格式编写查询:

$this->getEntity()
     ->whereBetween('timestamp_col1', [$start, $end])
     ->orWhereBetween('timestamp_col2', [$start, $end])
     ->get();

但以上述格式编写的缺点是,我必须为这两列分别手动指定开始和结束时间戳。有没有其他的方法来达到这个目的,或者我必须使用 whereRaw() 方法?谢谢。

9q78igpj

9q78igpj1#

你必须使用两个单独的 WHERE BETWEEN 条款。 where timestamp_col1 AND timestamp_col2 BETWEEN [...] 不是在做你认为它在做的事。
查询返回第一列计算结果所在的所有行 true 只适用于 WHERE BETWEEN 子句添加到第二列。
看看这个例子:http://sqlfiddle.com/#!9/f6fe15/1号楼

myzjeezk

myzjeezk2#

您不需要指定 $start 以及 $end 手动添加时间戳。你只需要转换一下 $start 以及 $end 使用php日期函数将值转换为时间戳或正确的日期时间格式,如下所述:

$start = date('Y-m-d H:i:s', strtotime($start));
$end = date('Y-m-d H:i:s', strtotime($end));
$this->getEntity()
     ->whereBetween('timestamp_col1', [$start, $end])
     ->orWhereBetween('timestamp_col2', [$start, $end])
     ->get();

相关问题