title: Select SUM from subquery while using whereHas in Laravel
body: <p>I have 2 tables, <code>customers</code> and <code>customer_invoices</code>, and I want to get all the customers with a condition on their invoices, and select specific columns (customers.id, customers.last_name, and the sum of the <code>total_price</code> of the invoices for each customer), I have this query :</p>
  
  <pre><code>$result = Customer::whereHas('customerInvoices', function(Builder $q) {
              $q-&gt;where('customer_invoices.status', 1);
          })-&gt;select([
              'customers.id',
              'customers.last_name',
              \DB::raw('SUM(customer_invoices.total_price) as sum')
          ])-&gt;get();
  </code></pre>
  
  <p><code>customerInvoices</code> is the relation :</p>
  
  <pre><code>public function customerInvoices() {
  
      return $this-&gt;hasMany(CustomerInvoice::class);
  }
  </code></pre>
  
  <p>I want to use subqueries instead of joins, so here I can't select this <code>\DB::raw('SUM(customer_invoices.total_price) as sum')</code>, or else I get this error of course :</p>
  
  <pre><code>"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer_invoices.total_price' in 'field list' (SQL: select `customers`.`id`, `customers`.`last_name`, SUM(customer_invoices.total_price) as sum from `customers` where exists (select * from `customer_invoices` where `customers`.`id` = `customer_invoices`.`customer_id` and `customer_invoices`.`status` = 1))"
  </code></pre>
  
  <p>How can I achieve this without using joins ?</p>