Search code examples
apieloquentwhere-clauselaravel-5.5eager-loading

whereHas is not working on NULL value


in laravel 5.5 whereHas() is not working on where value is NULL. my relationship with other model is one to many and and i want to pick the values from the model where value is equal to NULL . But instead of returning the specific values its returning all the value in result

 plans = Plan::with('objectives')->with('objectives.keyResults')
           ->whereHas('objectives', function($query) {
               $query->whereNull('entity_id');
               $query->whereNull('quarter_id');
       })->where('companyKey', Auth::user()->companyKey)->get();

Solution

  • You have to specify the constraint twice:

    $plans = Plan::with(['objectives' => function($query) {
            $query->whereNull('entity_id');
            $query->whereNull('quarter_id');
        }, 'objectives.keyResults'])
        ->whereHas('objectives', function($query) {
            $query->whereNull('entity_id');
            $query->whereNull('quarter_id');
        })->where('companyKey', Auth::user()->companyKey)
        ->get();