gpt4 book ai didi

mysql - Laravel 连接多个表

转载 作者:行者123 更新时间:2023-11-29 03:18:59 26 4
gpt4 key购买 nike

我有 3 个 mysql 表

**Clients**  
id | name

**Services**
id | name | foreign key -> client_id

**Payments**
id | payment_date | amount | foreign key -> service_id

客户端 Controller .php

$sumPayments = Payment::join('services', 'payments.service_id', '=', 'services.id')
->join('clients', 'clients.id', '=', 'services.client_id')->get();

客户端/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

我的模型中有 'belongsTo' 和 'hasMany'。
我尝试显示每个客户已支付的总付款额。请帮忙。

最佳答案

使用 withCount()方法:

Client::withCount('payments')->get();

f you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

因此,此代码将为每个客户端创建一个新的 payments_count 属性:

@foreach ($clients as $client)
{{ $client->payments_count }}
@endforeach

关于mysql - Laravel 连接多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com