我有3个mysql表
**Clients**
id | name
**Services**
id | name | foreign key -> client_id
**Payments**
id | payment_date | amount | foreign key -> service_id
ClientController.php
$sumPayments = Payment::join('services', 'payments.service_id', '=', 'services.id')
->join('clients', 'clients.id', '=', 'services.client_id')->get();
Clients / index.blade.php
@foreach($clients as $client)
<tr>
@foreach($service->payments as $payment)
@if($payment->service_id == $service->id)
<td>{{$sumPayments->where('service_id', '$services->id')->sum('payment_amount')}}</td>
@break
@endif
@endforeach
</tr>
@endforeach
属于&#39; belongsTo&#39;和&#39; hasMany&#39;在我的模特中。
我尝试显示每个客户支付的总金额。请帮忙。
答案 0 :(得分:0)
使用withCount()
方法:
Client::withCount('payments')->get();
如果您想要计算关系中的结果数而不实际加载它们,您可以使用
withCount
方法,这会在您生成的模型上放置{relation}_count
列。
因此,此代码将为每个客户端创建一个新的payments_count
属性:
@foreach ($clients as $client)
{{ $client->payments_count }}
@endforeach