Laravel 7 带连接的子查询

Laravel 7 subquery with join

我有两个 table 作为客户和交易。在交易中,存储与客户相关的所有交易。现在我想要来自客户 table 的所有数据,并且只需要从交易 table.

收到的金额总和

下面是查询

$customers = DB::table('customers')            
    ->join('transactions', 'customers.id', '=', 'transactions.custId')
    ->where('customers.status', 'Active')           
    ->select('customers.id', 'customers.custName', 'transactions.custTotalReceived as Received')
    ->paginate(100);

我想要的结果如下

客户编号 |客户名称 |收到

0001 |医学博士 | 2000

0002 |开发 | 5000

尝试在 customers.id(和 customers.custName)上使用 groupBy(),在 custTotalReceived 上使用 SUM()。类似于:

$customers = DB::table('customers')            
            ->join('transactions', 'customers.id', '=', 'transactions.custId')
            ->where('customers.status', 'Active')           
            ->select(DB::raw('customers.id, customers.custName, sum(transactions.custTotalReceived) as "Received"'))
            ->groupBy('customers.id', 'customers.custName')
            ->paginate(100);