Soura Ghosh
Soura Ghosh

Reputation: 917

SQL query in Laravel Eloquent Query

How to produce query like below in laravel eloquent

SELECT *
FROM TABLE
WHERE column1=value1 
and (
        (column2=value2 or column3=value3) 
     or (column4=value4 or column5=value5)
)

Please help.

Upvotes: 1

Views: 84

Answers (3)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Your query can be expressed as

SELECT * 
FROM table 
WHERE column1=value1 
AND (
       column2=value2 
    or column3=value3 
    or column4=value4 
    or column5=value5
)

To use above in laravel you can follow Parameter Grouping guide from docs

DB::table('table')
    ->where('column1', $value1)
    ->where(function ($query) use ($value2, $value3, $value4, $value5) {
        $query->where('column2', $value2)
          ->orWhere('column3', $value3)
          ->orWhere('column4', $value4)
          ->orWhere('column5', $value5)
          ;
    })
    ->get();

Upvotes: 2

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Try it

DB::table('the_table')
    ->where('column1', 'value1')
    ->where(function ($query) {
        $query->where(function ($query) {
            $query->where('column2', 'value2')
                ->orWhere('column3', 'value3');
        })->orWhere(function ($query) {
            $query->where('column4', 'value4')
            ->orWhere('column5', 'value5');
        });
    })->get();

Upvotes: 0

Namoshek
Namoshek

Reputation: 6544

You need to use two nested where() statements:

DB::table('the_table')
    ->where('column', 'val')
    ->where(function ($q) {
        $q->where('column1', 'val1')
            ->orWhere('column2', 'val2');
    })
    ->where(function ($q) {
        $q->where('column3', 'val3')
            ->orWhere('column4', 'val4');
    })
    ->get()

If you need to pass a variable to the nested where(), you need to add a use on the inline function:

DB::table('the_table')
    ->where('column', $val)
    ->where(function ($q) use ($val1, $val2) {
        $q->where('column1', $val1)
            ->orWhere('column2', $val2);
    })
    ->where(function ($q) {
        $q->where('column3', 'val3')
            ->orWhere('column4', 'val4');
    })
    ->get()

Upvotes: 0

Related Questions