【发布时间】:2014-04-14 20:35:40
【问题描述】:
如何将以下查询转换为 Laravel 4 eloquent ORM?
select * from table where ((starttime <= ? and endtime >= ?) or (starttime <= ? and endtime >= ?) or (starttime >= ? and endtime <= ?))
【问题讨论】:
如何将以下查询转换为 Laravel 4 eloquent ORM?
select * from table where ((starttime <= ? and endtime >= ?) or (starttime <= ? and endtime >= ?) or (starttime >= ? and endtime <= ?))
【问题讨论】:
像这样:
<?php
$results = DB::table('table')
->where(function($query) use ($starttime,$endtime){
$query->where('starttime', '<=', $starttime);
$query->where('endtime', '>=', $endtime);
})
->orWhere(function($query) use ($otherStarttime,$otherEndtime){
$query->where('starttime', '<=', $otherStarttime);
$query->where('endtime', '>=', $otherEndtime);
})
->orWhere(function($query) use ($anotherStarttime,$anotherEndtime){
$query->where('starttime', '>=', $anotherStarttime);
$query->where('endtime', '<=', $anotherEndtime);
})
->get();
查看documentation,了解您可以使用 Eloquent 和Query Builder 做的更酷的事情。
//编辑: 甚至将整个 where 子句包裹在大括号中(就像在您的问题中一样),您可以这样做:
<?php
$results = DB::table('table')
//this wraps the whole statement in ()
->where(function($query) use ($starttime,$endtime, $otherStarttime,$otherEndtime, $anotherStarttime,$anotherEndtime){
$query->where(function($query) use ($starttime,$endtime){
$query->where('starttime', '<=', $starttime);
$query->where('endtime', '>=', $endtime);
});
$query->orWhere(function($query) use ($otherStarttime,$otherEndtime){
$query->where('starttime', '<=', $otherStarttime);
$query->where('endtime', '>=', $otherEndtime);
});
$query->orWhere(function($query) use ($anotherStarttime,$anotherEndtime){
$query->where('starttime', '>=', $anotherStarttime);
$query->where('endtime', '<=', $anotherEndtime);
});
})
->get();
【讨论】:
$query->where(function($query) use ($starttime, $endtime) { ... }); 以下是一些示例:php.net/manual/en/functions.anonymous.php(特别是示例 #3)