Laravel - Group By & Key By together
<p>Assuming I have the following MySQL tables to represent pricebooks, items and the relationship between them:</p>

<pre><code>item - item_id|name|...etc
pricebook - pricebook_id|name|...etc
</code></pre>

<p>and the following <code>pivot table</code></p>

<pre><code>pricebook_item - pricebook_id|item_id|price|...etc
</code></pre>

<p>I have the correlating Eloquent models: <code>Pricebook</code>, <code>Item</code> and a repository named <code>PricebookData</code> to retrieve the necessary information.</p>

<p>Within the <code>PricebookData</code> repository, I need to get the pricebook data grouped by pricebook id and then keyed by item_id for easy access on client side.</p>

<p>If I do:</p>

<pre><code>Pricebook::all()-&gt;groupBy('pricebook_id');
</code></pre>

<p>I get the information grouped by the <code>pricebook_id</code> but inside each pricebook the keys are simple numeric index (it arrives as js array) and not the actual product_id. So when returning to client side Javascript, the result arrives as the following:</p>

<pre><code>pricebookData: {1: [{}, {}, {}...], 2: [{}, {}, {}...]}
</code></pre>

<p>The problem with the prices arriving as array, is that I can not access it easily without iterating the array. Ideally I would be able to receive it as:</p>

<pre><code> pricebookData: {1: {1001:{}, 1002: {}, 1003: {}}, 2: {1001:{}, 1002: {}, 1003: {}}}
//where 1001, 1002, 1003 are actual item ids
//with this result format, I could simply do var price = pricebookData[1][1001]
</code></pre>

<p>I've also tried the following but without success: </p>

<p><code>Pricebook::all()-&gt;keyBy('item_id')-&gt;groupBy('pricebook_id');</code></p>

<p>The equivalent of what I am trying to avoid is:</p>

<pre><code>$prices = Pricebook::all();
$priceData = [];
foreach ($prices as $price) 
{
   if (!isset($priceData[$price-&gt;pricebook_id])) 
   {
      $priceData[$price-&gt;pricebook_id] = [];
   }
   $priceData[$price-&gt;pricebook_id][$price-&gt;item_id] = $price;
}
return $priceData;
</code></pre>

<p>I am trying to find a pure elegant Eloquent/Query Builder solution.</p>