Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, as far as naming conventions go, to make things easier to understand: The <code>rating()</code> method within your tutorial method should be called <code>ratings()</code>, so when you grab your ratings, it will look better (<code>$tutorial-&gt;ratings</code>)</p> <p>After renaming this, in your view, while looping through the array of $tutorials, you could access the ratings of each one like this:</p> <pre><code>foreach($tutorials as $tutorial) { $ratings = $tutorial-&gt;ratings; } </code></pre> <p>Which would retrieve the ratings object of each.</p> <p>What you should know is that <strong>you can create properties for your model if you need to return the calculation of the ratings, instead of the ORM objects</strong></p> <p>For example, if each rating is a number from 1-5 in the ratings table stored in an <code>amount</code> column, you can do this to set the average of each rating as a property:</p> <pre><code>class Tutorial extends Eloquent { protected $table = 'tutorials'; public function ratings() { return $this-&gt;hasMany('Rating'); } public function getRating() { // Grab the ratings from this tutorial $ratings = $this-&gt;ratings; $summedRatings = 0; // Loop through them all and add them together foreach($ratings as $rating) { $summedRatings += $rating-&gt;amount; } // Return the calculated average return $summedRatings / count($ratings); } } </code></pre> <p>Then in your view, you can echo out the property as if it were part of the database</p> <pre><code>foreach($tutorials as $tutorial) { echo $tutorial-&gt;rating; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload