0

I have 5 database rows with the same client_id, 3 labelled completed, Yes.

This code pulls through 3 results as expected:

$indGoal = $client->indGoal()->where('completed','=','Yes')->get();

This code pulls through no results: I would expect 2.

$indGoal = $client->indGoal()->where('completed','!=','Yes')->get();

This question suggests adding ->orWhereNull('completed') - which works, but ignores the client_id relationship. The request brings through all non-Yes results, regardless of $client

My Client model for reference:

public function indGoal()
{
    return $this->hasMany('App\Models\IndGoal');
}
Jerodev
  • 32,252
  • 11
  • 87
  • 108
Mike Thrussell
  • 4,175
  • 8
  • 43
  • 59

1 Answers1

1

You should group orWhere filters in a callback so they don't interfere with existing filters.

$indGoal = $client->indGoal()
    ->where(function ($query) {
        $query->orWhere('completed', '!=', 'yes')
            ->orWhereNull('completed');
    })
    ->get();

This way, the query builder knows any of the grouped conditions should be true and all other conditions are independent.

Jerodev
  • 32,252
  • 11
  • 87
  • 108