Laravel雄辩的ORM集团在哪里

时间:2014-03-11 09:57:56

标签: laravel-4 eloquent

如何将以下查询转换为Laravel 4 eloquent ORM?

select * from table where ((starttime <= ? and endtime >= ?) or (starttime <= ? and endtime >= ?) or (starttime >= ? and endtime <= ?))

1 个答案:

答案 0 :(得分:68)

像这样:

<?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();
相关问题