title: Laravel HasManyThrough with 3-way pivot table
body: <p>I have the following models</p>
  
  <p><strong>Recipe</strong></p>
  
  <pre><code>public function ingredientRecipeUnits()
  {
      return $this-&gt;hasMany(IngredientRecipeUnit::class);
  }
  </code></pre>
  
  <p><strong>Ingredient</strong></p>
  
  <pre><code>public function ingredientRecipeUnits()
  {
      return $this-&gt;hasMany(IngredientRecipeUnit::class);
  }
  </code></pre>
  
  <p><strong>Unit</strong></p>
  
  <pre><code>public function ingredientRecipeUnits()
  {
      return $this-&gt;hasMany(IngredientRecipeUnit::class);
  }
  </code></pre>
  
  <p>and a pivot table (in its own model) connecting all three:</p>
  
  <p><strong>IngredientRecipeUnit</strong></p>
  
  <pre><code>public function ingredient()
  {
      return $this-&gt;belongsTo(Ingredient::class);
  }
  
  public function recipe()
  {
      return $this-&gt;belongsTo(Recipe::class);
  }
  
  public function unit()
  {
      return $this-&gt;belongsTo(Unit::class);
  }
  </code></pre>
  
  <p>I would like to fetch all Recipes through the ingredient model.</p>
  
  <p>For this I made the following relationship:</p>
  
  <pre><code>public function recipes() {
      return $this-&gt;hasManyThrough(
          Recipe::class,      
          IngredientRecipeUnit::class, 
          'ingredient_id', 
          'id'
      );
  }
  </code></pre>
  
  <p>This generates an <strong><em>incorrect</em></strong> query looking like this</p>
  
  <pre class="lang-sql prettyprint-override"><code>select * from `recipes` 
  inner join `ingredient_recipe_units` 
  on `ingredient_recipe_units`.`id` = `recipes`.`id` 
  where `ingredient_recipe_units`.`ingredient_id` = ?
  </code></pre>
  
  <p>while in reality the query should look like this. (Notice subtle change of <code>id</code> -> <code>recipe_id</code> on line 3)</p>
  
  <pre class="lang-sql prettyprint-override"><code>select * from 'recipes'
  inner join `ingredient_recipe_units`
  on `ingredient_recipe_units`.`recipe_id` = `recipes`.`id` 
  where `ingredient_recipe_units`.`ingredient_id` = ?
  </code></pre>
  
  <p>Besides sending a pull-request to the Eloquent repo to add an extra Parameter or using raw SQL; is there any way to solve this?</p>