title: How to group on multiple fields including nested eager columns
body: <p>I have some carts, products and users.
  I try to get statistics like number of carts per user. And here are my models:</p>
  <ul>
  <li><p>user.php</p>
  <pre><code>class User {
      public function products()
      {
          return $this-&gt;hasMany(Product::class, 'user_id');
      }
  }
  </code></pre>
  </li>
  <li><p>cart.php</p>
  <pre><code>class Cart {
  
      public function products()
      {
         return $this-&gt;hasMany(Product::class, 'cart_id');
      }     
  }
  </code></pre>
  </li>
  <li><p>product.php</p>
  <pre><code>class Product {
  
      public function user()
      {
          return $this-&gt;belongsTo('User', 'user_id');
      }
  
      public function cart()
      {
          return $this-&gt;belongsTo(Cart::class, 'cart_id');
      }      
  }
  </code></pre>
  </li>
  </ul>
  <p>Here is my query:</p>
  <pre><code>$query = Cart::query()
          -&gt;whereHas('products', function ($query) use ($filter) {
              $query-&gt;where('whatever', $filter);
          })
          -&gt;join('product', 'product.cart_id', '=', 'cart.id')
          -&gt;join('users', 'users.id', '=', 'product.user_id')
          -&gt;groupBy('users.id')
          -&gt;select('users.id as user_id')
          -&gt;select('users.name')
          -&gt;selectRaw('count(cart.id) as numberOfCarts')
          -&gt;selectRaw('SUM(price)')
          -&gt;orderBy('users.name')
          -&gt;get();
  </code></pre>
  <p>What I get is number of products per user, but I want number of carts per user. when I try to group using <em>cart.id</em> like <code>groupBy(['user.id', 'cart.id'])</code>, it is worse: I get several times the same user and at each time the number of products in cart. And this total gives the same as total of number of carts get previously.</p>
  <p>I have added jointure because I don't make it work by trying grouping on nested eager relationship. So I make it simplier.</p>
  <p>How to fix grouping to count users carts and not their products ?</p>