我该如何将以下查询语句转换为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();
查看文档,了解使用Eloquent和查询构建器的更多酷炫操作。
//编辑:要将整个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();
$jkw = DB::table('table') //这将整个语句包裹在()中 ->where(function($query) use ($starttime,$endtime, $otherStarttime,$otherEndtime, $anotherStarttime,$anotherEndtime){
$query->where(function($query) use ($starttime,$endtime){
$query->where('starttime', '<=', $starttime)
->where('endtime', '>=', $endtime);
});
$query->orWhere(function($query) use ($otherStarttime,$otherEndtime){
$query->where('starttime', '<=', $otherStarttime)
->where('endtime', '>=', $otherEndtime);
});
$query->orWhere(function($query) use ($anotherStarttime,$anotherEndtime){
$query->where('starttime', '>=', $anotherStarttime)
->where('endtime', '<=', $anotherEndtime);
});
})
->get();
轻松愉快 XD
$query->where(function($query) use ($starttime, $endtime) { ... });
这里有一些示例:http://www.php.net/manual/en/functions.anonymous.php(特别是示例#3) - Quasdunk