title: How to make two Laravel Eloquent queries into a single one (so I hit the database once instead of 2 times)
body: <p>Say I have 3 tables in my database. </p>
  
  <p>'my_recipe', 'my_inventory' and 'ingredient'. </p>
  
  <p>The 'my_recipe' table stores a list of raw_id's based on the 'ingredient' table and the 'quantity' need for the recipe. The 'my_inventory' table stores a list of raw_id's and 'have_quantity'.</p>
  
  <p>So let's take a look at what I currently have at the moment. I have the following 2 queries:</p>
  
  <p>First Query:</p>
  
  <pre><code>$recipe = DB::table('my_recipe as tA')
      -&gt;leftJoin('ingredient as tB', 'tA.raw_id', '=', 'tB.raw_id')
      -&gt;select('tA.user as user', 'tA.raw_id as raw_id', 'tA.quantity as quantity',
          'tB.ingredient_name as ingredient_name')
      -&gt;where('user', '=', $user)
      -&gt;where('raw_id', '=', $raw_id)
      -&gt;get();
  </code></pre>
  
  <p>Second Query:</p>
  
  <pre><code>$inventory = DB::table('my_inventory as tA')
      -&gt;leftJoin('ingredient as tB', 'tA.raw_id', '=', 'tB.raw_id')
      -&gt;select('tA.user as user', 'tA.have_quantity as have_quantity',
          'tB.ingredient_name as ingredient_name')
      -&gt;where('user', '=', $user)
      -&gt;get();
  </code></pre>
  
  <p>The first query returns results that look something like this:</p>
  
  <pre><code>{"user":"jack","raw_id":"853","quantity":2,"ingredient_name":"apple"},
  {"user":"jack","raw_id":"853","quantity":4,"ingredient_name":"peach"}
  </code></pre>
  
  <p>The second query returns results that look something like this:</p>
  
  <pre><code>{"user":"jack","have_quantity":30,"ingredient_name":"apple"},
  {"user":"jack","have_quantity":20,"ingredient_name":"apple"},
  {"user":"jack","have_quantity":10,"ingredient_name":"apple"},
  {"user":"jack","have_quantity":1,"ingredient_name":"peach"},
  {"user":"jack","have_quantity":1,"ingredient_name":"peach"}
  </code></pre>
  
  <p>Notice in the second query results I have to get the sum of the ingredients based on the 'ingredient_name' for my ideal output.</p>
  
  <p>How can I get my ideal output in a single query?</p>
  
  <p>My ideal output would look something like this:</p>
  
  <pre><code>{"user":"jack","raw_id":"853","quantity":2,"ingredient_name":"apple","have_quantity":60},
  {"user":"jack","raw_id":"853","quantity":4,"ingredient_name":"peach","have_quantity":2}
  </code></pre>
  
  <p>It's basically the results of the first query with 'have_quantity' totals from the second query.</p>
  
  <p>EDIT:</p>
  
  <p>my_recipe Model:</p>
  
  <pre><code>'user', 'raw_id', 'quantity'
  </code></pre>
  
  <p>my_inventory Model:</p>
  
  <pre><code>'user', 'raw_id', 'have_quantity'
  </code></pre>
  
  <p>ingredient Model:</p>
  
  <pre><code>'raw_id', 'ingredient_name'
  </code></pre>
  
  <p>Note: In the ingredient model there can be rows with the same 'ingredient_name' but have different 'raw_id'.</p>