title: Laravel 5.7 - Eloquent Query that checks if not equal to id or null AND not equal to another id and a team_id not in (?, ?)
body: <p>I'm trying to create a scope on my model that queries for results that are not related to user based on the following possibilities:
  1. The <code>assigned_user_id</code> is not null and <code>reported_by</code> doesn't match and any of the user's team_ids (one-to-many user to teams) match the <code>assigned_team_id</code>
  AND 
  2. The <code>assigned_user_id</code> does not match and <code>reported_by</code> doesn't match and any of the user's team_ids (one-to-many user to teams) match the <code>assigned_team_id</code></p>
  
  <p>The only tricky part for me really is that the assigned_user_id is nullable. assigned_team_id is required and reported_by is required. This is my current attempt:</p>
  
  <pre><code>public function scopeNotRelativeTo($query, User $user)
  {
      $teamIDs = $user-&gt;teams-&gt;pluck('id');
  
      $query-&gt;whereNull('assigned_user_id')
            -&gt;orWhere('assigned_user_id', '!=', $user-&gt;id)
            -&gt;where('reported_by', '!=', $user-&gt;id)
            -&gt;whereNotIn('assigned_team_id', $teamIDs);
  }
  </code></pre>
  
  <p>This is returning 46 results and I am expecting 41, so it's not quite right. The <code>toSql()</code> is </p>
  
  <pre><code>"select * from \"bugs\" where (\"assigned_user_id\" is null or \"assigned_user_id\" != ? and \"reported_by\" != ? and \"assigned_team_id\" not in (?, ?)) and \"bugs\".\"deleted_at\" is null order by \"created_at\" desc"
  </code></pre>
  
  <p>which looks close, but it is still clearly imperfect. I can definitely see that there are results slipping through the cracks with matching team_ids mostly. Pseudo code version would be <code>Give me results where the assigned_user_id is not null AND reported_by doesn't match userId AND assigned_team_id not in user-&gt;teamIds OR assigned_user_id doesn't match userId AND reported_by doesn't match userId and assigned_team_id is not in user-&gt;teamIds</code>.</p>