Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 <= ?)) 
like image 848
Bishwarup Das Avatar asked Mar 11 '14 09:03

Bishwarup Das


1 Answers

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(); 
like image 86
Quasdunk Avatar answered Sep 30 '22 17:09

Quasdunk