Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Eloquent where and or in Clauses

i try to get results from table with multiple where and/or clauses.

My SQL statement is:

SELECT * FROM tbl WHERE m__Id = 46 AND t_Id = 2 AND (Cab = 2 OR Cab = 4) 

How i can get this with Laravel Eloquent?

My Code in Laravel is:

$BType = CabRes::where('m_Id', '=', '46')                         ->where('t_Id', '=', '2')                         ->where('Cab', '2')                         ->orWhere('Cab', '=', '4')                         ->get(); 
like image 773
Sinisa P. Avatar asked May 25 '15 08:05

Sinisa P.


2 Answers

Using advanced wheres:

CabRes::where('m__Id', 46)       ->where('t_Id', 2)       ->where(function($q) {           $q->where('Cab', 2)             ->orWhere('Cab', 4);       })       ->get(); 

Or, even better, using whereIn():

CabRes::where('m__Id', 46)       ->where('t_Id', 2)       ->whereIn('Cab', $cabIds)       ->get(); 
like image 137
Limon Monte Avatar answered Sep 20 '22 14:09

Limon Monte


Also, if you have a variable,

CabRes::where('m_Id', 46)       ->where('t_Id', 2)       ->where(function($q) use ($variable){           $q->where('Cab', 2)             ->orWhere('Cab', $variable);       })       ->get(); 
like image 28
Jaber Al Nahian Avatar answered Sep 20 '22 14:09

Jaber Al Nahian