Laravel eloquent ORM group where

前端 未结 1 385
情话喂你
情话喂你 2021-02-05 01:05

How do I convert the following query to Laravel 4 eloquent ORM?

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


        
1条回答
  •  不知归路
    2021-02-05 02:03

    Like this:

    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();
    

    Have a look at the documentation for even more cool stuff you can do with Eloquent and the Query Builder.

    //Edit: To even wrap the whole where-clause in braces (like it is in your question), you can do this:

    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();
    

    0 讨论(0)
提交回复
热议问题