Home > Mobile >  how to use whereHas in laravel
how to use whereHas in laravel

Time:05-03

I am new to laravel, I need to create a query for the db,

 $query = Deal::query();

I want to use the wherehas operator. this is my code that is worked.

else if ($group_by == 'precedence') {
                if($get_deals_for == 'noprecedence'){
                    $get_deals_for = 0;
                }
                $precedenceStatus = $get_deals_for;
                $query-> where('precedence', '=', $precedenceStatus);
            //    \Log::info('The request precedence: '.$precedenceStatus);
               

            }

I want to add this code also to the query

if($person) {
                    $query->whereHas('personnel', function ($subQuery) use ($person) {
                        $subQuery->where('id', '=', $person);
                    });
                }

So I need to change the first code? how I can convert the first code to wherehas? the first code is from table called deal, the second section is from realtionship called personnel. the second section worked in other places in the code, I just need to fix the first section and not understand what to write in the use

I try this and get error on the last }

else if ($group_by == 'precedence') {
                if($get_deals_for == 'noprecedence'){
                    $get_deals_for = 0;
                }
                $precedenceStatus = $get_deals_for;
                $query-> where('precedence', '=', $precedenceStatus)
                      -> when ($person, function($query) use($person) {
                        $query->whereHas('personnel', function ($query) use ($person) {
                            $query->where('id', '=', $person);
                        });
                    })
                }

CodePudding user response:

There is a method you can use called when(, so that you can have cleaner code. The first parameter if true will execute your conditional statement.

https://laravel.com/docs/9.x/queries#conditional-clauses

$query
  ->where('precedence', '=', $precedenceStatus)
  ->when($person, function($query) use($person) {
      $query->whereHas('personnel', function ($query) use ($person) {
                        $query->where('id', '=', $person);
                    });
  })

You should also be able to clean up your precedence code prior to that using when( to make the entire thing a bit cleaner.

  • Related