title: Laravel Eloquent query with relationship table with where and wherehas
body: <p>Following query is ignoring the <code>where('contact_id',$id)</code> causing to return results that does not belong to this contact. Why?</p>
  <pre><code>Transaction::where('contact_id',$id)
              -&gt;with('allocations')
              -&gt;whereHas(&quot;allocations&quot;,function ($query){
              $query-&gt;select('transaction_id')
                  -&gt;havingRaw('transactions.amount &gt; sum(amount)')
                  -&gt;groupBy('transaction_id');
              })
              -&gt;orDoesntHave(&quot;allocations&quot;)
              -&gt;get();
  </code></pre>
  <p>if I remove the whereHas part, it is bringing back the correct result. But I need the whereHas part.</p>
  <pre><code>            -&gt;whereHas(&quot;allocations&quot;,function ($query){
              $query-&gt;select('transaction_id')
                  -&gt;havingRaw('transactions.amount &gt; sum(amount)')
                  -&gt;groupBy('transaction_id');
              })
              -&gt;orDoesntHave(&quot;allocations&quot;)
  </code></pre>
  <p>Basically, I am trying to query for transactions where the transaction amount is greater than the sum of allocations (transaction hasMany allocations) for that transaction.</p>