title: How to GROUP and SUM a pivot table column in Eloquent relationship?
body: <p>In Laravel 4; I have model <code>Project</code> and <code>Part</code>, they have a many-to-many relationship with a pivot table <code>project_part</code>. The pivot table has a column <code>count</code> which contains the number of a part ID used on a project, e.g.:</p>
  
  <pre><code>id  project_id  part_id count
  24  6           230     3
  </code></pre>
  
  <p>Here the <code>project_id</code> 6, is using 3 pieces of <code>part_id</code> 230.</p>
  
  <p>One part may be listed multiple times for the same project, e.g.:</p>
  
  <pre><code>id  project_id  part_id count
  24  6           230     3
  92  6           230     1
  </code></pre>
  
  <p>When I show a parts list for my project I do not want to show <code>part_id</code> twice, so i group the results.</p>
  
  <p>My <strong>Projects</strong> model has this:</p>
  
  <pre><code>public function parts()
  {
      return $this-&gt;belongsToMany('Part', 'project_part', 'project_id', 'part_id')
           -&gt;withPivot('count')
           -&gt;withTimestamps()
           -&gt;groupBy('pivot_part_id')
  }
  </code></pre>
  
  <p>But of course my <code>count</code> value is not correct, and here comes my problem: <strong>How do I get the sum of all grouped parts for a project?</strong></p>
  
  <p>Meaning that my parts list for <code>project_id</code> 6 should look like:</p>
  
  <pre><code>part_id count
  230     4
  </code></pre>
  
  <p>I would really like to have it in the <code>Projects</code>-<code>Parts</code> relationship so I can eager load it.</p>
  
  <p>I can not wrap my head around how to do this without getting the N+1 problem, any insight is appreciated.</p>
  
  <hr>
  
  <p><strong>Update:</strong> As a temporary work-around I have created a presenter method to get the total part count in a project. But this is giving me the N+1 issue.</p>
  
  <pre><code>public function sumPart($project_id)
  {
      $parts = DB::table('project_part')
          -&gt;where('project_id', $project_id)
          -&gt;where('part_id', $this-&gt;id)
          -&gt;sum('count');
  
      return $parts;
  }
  </code></pre>