How to use multiple OR, AND conditions in Laravel queries

I need help to request in laravel

My user request: (Return the correct result)

Select * FROM events WHERE status = 0 AND (type="public" or type = "private")

how to write this request in Laravel.

Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get();

But it returns all public events whose status is also not 0.

I am using Laravel 5.4

+6
source share
4 answers

Finish closing at where():

Event::where('status' , 0)
     ->where(function($q) {
         $q->where('type', 'private')
           ->orWhere('type', 'public');
     })
     ->get();

https://laravel.com/docs/5.4/queries#parameter-grouping

+3
source

Use this

$event = Event::where('status' , 0);

$event = $event->where("type" , "private")->orWhere('type' , "public")->get();

or

Event::where('status' , 0)
     ->where(function($result) {
         $result->where("type" , "private")
           ->orWhere('type' , "public");
     })
     ->get();
+1
source

...

select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private");

Eloquent:

$events = Event::where('status', 0)
    ->whereIn('type', ['public', 'private'])
    ->get();

OR/AND, :

$events = Event::where('status', 0)
    ->where(function($query) {
        $query->where('type', 'public')
            ->orWhere('type', 'private');
    })->get();
0

. .

$rand_word=Session::get('rand_word');
$questions =DB::table('questions')
    ->where('word_id',$rand_word)
    ->where('lesson_id',$lesson_id)
    ->whereIn('type', ['sel_voice', 'listening'])
    ->get();
0

Source: https://habr.com/ru/post/1016519/


All Articles