提取汇总金额列的数据,以便按客户、月份和年份对结果进行分组

Pull data summing up the amount column such that the result is grouped by customers, month and year

我有一个客户table和一个客户交易table.

下面是客户的table。

下面是客户交易table。

下面是我想要实现的:

我希望能够对金额列求和,以便结果按客户、月份和年份分组。

这是我目前所做的:

我为 CustomersCustomers transactions 创建了一个模型。我在客户交易模型中有这种关系:

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

我还有一个客户控制器,我在其中具有获取数据的逻辑。在我的 CustomerController 文件中:

    public function index()
    {
        $transactions = CustomerTransaction::with('customer')->get();

        dd($transactions);
    }

我能够解决它。在 CustomerController 文件中,这是我现在在索引方法中的内容:

$transactions = CustomerTransaction::with('customer')
->selectRaw('customer_id, sum(amount) as amount, MONTH(date_created) as month, YEAR(date_created) as year')
->groupBy('customer_id', 'month', 'year')
->get();

那么在我看来,我有这个:

                    <table class="table">
                        <tr>
                            <th>S/N</th>
                            <th>Name</th>
                            <th>Amount</th>
                            <th>Year month</th>
                        </tr>
                        @foreach ($transactions as $transaction)
                            <tr>
                                <td>{{ $loop->iteration }}</td>
                                <td>{{ $transaction->customers->name }}</td>
                                <td>{{ $transaction->amount }}</td>
                                <td>{{ $transaction->year }}-{{ sprintf('%02d', $transaction->month) }}</td>
                            </tr>
                        @endforeach
                    </table>

我能够编写 SQL 查询:

select ROW_NUMBER() OVER(ORDER BY (select null)) as id,
name as `Customer name`,
sum(amount) as `Total amount`,
concat(YEAR(date_created), '-',
lpad(MONTH(date_created), 2, '0')) as `Year month`
from customer_transactions
join customers on customers.id=customer_transactions.customer_id
group by `customer_id`, `Year month`
order by `customer_id`, `Year month`