Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

How do I say WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)

For more complicated queries am I supposed to use raw SQL?

like image 253
Farzher Avatar asked Jun 08 '13 01:06

Farzher


People also ask

How do I combine two tables in eloquent Laravel?

If you want to join two or multiple tables in laravel then you can use laravel eloquent join(), left join(), right join(), cross join(). And another option to join two or multiple table, you can use laravel eloquent relationships instead of laravel join.

What is the difference between Laravel find and where?

find returns an object instance of the model while where which uses the get method returns a collection. find returns null if no row has been returned while where which uses the get method always returns a collection which can be empty when no results have been returned from the database.

Which is better eloquent or query builder in Laravel?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

How do I use whereBetween in Laravel?

The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.


2 Answers

Make use of Logical Grouping (Laravel 7.x/4.2). For your example, it'd be something like this:

Model::where(function ($query) {     $query->where('a', '=', 1)           ->orWhere('b', '=', 1); })->where(function ($query) {     $query->where('c', '=', 1)           ->orWhere('d', '=', 1); }); 
like image 86
rmobis Avatar answered Sep 16 '22 17:09

rmobis


If you want to use parameters for a,b,c,d in Laravel 4

Model::where(function ($query) use ($a,$b) {     $query->where('a', '=', $a)           ->orWhere('b', '=', $b); }) ->where(function ($query) use ($c,$d) {     $query->where('c', '=', $c)           ->orWhere('d', '=', $d); }); 
like image 42
Yilmazerhakan Avatar answered Sep 17 '22 17:09

Yilmazerhakan