title: Sort Eloquent Models by related table
body: <p>I have a table in which I save movies, and then I have another table, where I save the price for the movie dependent on the age. Each age has a different price. What I now want to do, is to get all movies for a specific age, and sort it by price. </p>
  
  <p>My <code>movies</code> table looks like this</p>
  
  <p><code>id - name</code></p>
  
  <p>My <code>prices</code> table looks like this</p>
  
  <p><code>id - movie_id - age - price</code> </p>
  
  <p>To get the data I'm using the following code</p>
  
  <pre><code>/** @var Builder $movies */
  // We now get only the movies where the user's age is listed in the price table
  $movies = Movie::whereHas('prices', function ($query) use ($age) {
      /** @var Builder $query */
      $query-&gt;where('age', $age);
  });
  </code></pre>
  
  <p>That way I'm getting only movies which are for a specific age. However, now I want to sort them by price. How would I do that? I tried to use <code>with</code> instead of <code>whereHas</code> to get the relation and then order it by the pivot table, but the problem is, that when I use <code>with</code> I'm getting 83 movies, however, when using <code>whereHas</code> I'm getting 76 results. 76 is the correct number, since when I use SQL to get all movies with prices for 23 years old I'm getting 76</p>
  
  <p><code>SELECT COUNT(id) FROM prices WHERE age = 23; // 76</code></p>
  
  <p>When googling I found many people who where using <code>join</code> methods instead of the Eloquent methods. Is this really the only possibility to go? </p>