Can a query be made in larvael where the two conditions are met where to make the query?

2

I need to make a query where both where are fulfilled, in this case that as long as user X and the status is PUBLISHED or DRAFT shows it, I currently have:

$properties = Accommodation::where("user_id", $id)                         
                            ->where("status", 'PUBLISHED')                 
                            ->orWhere("status", 'DRAFT')                   
                            ->get();

The problem is that it shows all of them, it does not filter by users.

Something like:

$properties = Accommodation::where("user_id", $id)AND                      
                           ->where("status", 'PUBLISHED')               
                          AND->orWhere("status", 'DRAFT')                  
                          ->get();
    
asked by Joe 22.12.2018 в 18:29
source

4 answers

3

I really do not see why complicating the query with a closure when resolved by a simple whereIn, as in "normal" SQL:

$properties = Accommodation::whereUserId($id)                         
                    >whereIn('status', ['PUBLISHED', 'DRAFT'])                
                    ->get();
    
answered by 22.12.2018 / 20:15
source
1

The problem is that you are not correctly grouping your conditions in the query. You can solve it by using Query Builder and doing the grouping of parameters. Your code should look something like this:

DB::table('accommodation') // <- Nombre de tu tabla.
            ->where('user_id', '=', $id) // <- tu condición 'general'
            ->where(function ($query) {
                $query->where('status', '=', 'PUBLISHED')//<- agrupamiento de condiciones
                      ->orWhere('status', '=', 'DRAFT');
            })
            ->get();
    
answered by 22.12.2018 в 18:42
1

Maintaining the use of the Accomodation model, you can pass as a second argument of the first where an anonymous function where you include both the where and the orWhere in this way

$properties = Accommodation::where("user_id", $id)                         
                           ->where(funtion($query){
                               $query->where("status", 'PUBLISHED')
                                     ->orWhere("status", 'DRAFT');
                           })->get();
    
answered by 22.12.2018 в 18:48
0

All you have to do is remove the AND, it would look something like this:

$properties = Accommodation::where("user_id", $id)                      
    ->where("status", 'PUBLISHED')               
    ->orWhere("status", 'DRAFT')                  
    ->get();
    
answered by 22.12.2018 в 19:11