title: Laravel count column of related model
body: <p>I want to count the number of upvotes and downvotes from <code>ScripRating</code> for a certain <code>Script</code>.</p>
  
  <p>Script.php:</p>
  
  <pre><code>public function ratings()
  {
      return $this-&gt;hasMany('ScriptRating');
  }
  </code></pre>
  
  <p>ScriptRating.php:</p>
  
  <pre><code>public function script()
  {
      return $this-&gt;belongsTo('Script');
  }
  </code></pre>
  
  <p>The script_rating database table:</p>
  
  <pre><code>id (primary, increments)
  script_id(integer)
  rating(integer) &lt;-- Can be either 1 (upvote) or -1 (downvote)
  </code></pre>
  
  <p>To retrieve a script and display the ratings:</p>
  
  <pre><code>$script = Script::where('title', '=', $title)-&gt;get();
  {{ $script-&gt;ratings }}
  </code></pre>
  
  <p>This works fine, it returns an array: <code>[{"id":1,"script_id":1,"rating":1}]</code>. But at this point I'm stuck. How could I count the total upvotes and downvotes for a certain script?</p>
  
  <p>I also have one more small question what I'm finding confusing. This does the same as the code above:</p>
  
  <pre><code>$script = Script::where('title', '=', $title)-&gt;with('ratings')-&gt;get();
  {{ $script-&gt;ratings }}
  </code></pre>
  
  <p>What is the difference between these two methods and which one should I use?</p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I made three scopes:</p>
  
  <pre><code>public function scopeTotalRating($query, $scriptId) {
      return $query-&gt;where('script_id', $scriptId)-&gt;get()-&gt;sum('rating');
  }
  
  public function scopeThumbsUp($query, $scriptId) {
      return $query-&gt;where('script_id', $scriptId)-&gt;having('rating', '=', 1)-&gt;get()-&gt;sum('rating');
  }
  
  public function scopeThumbsDown($query, $scriptId) {
      return $query-&gt;where('script_id', $scriptId)-&gt;having('rating', '=', -1)-&gt;get()-&gt;sum('rating');
  }
  </code></pre>
  
  <p>And display them as following:</p>
  
  <pre><code>{{ ScriptRating::thumbsUp($script-&gt;id) }}
  </code></pre>