Search code examples
laravel-4eloquent

Laravel eloquent ORM group where


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

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

Solution

  • Like this:

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

    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:

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