【问题标题】:Laravel joining multiple tablesLaravel 连接多个表
【发布时间】:2018-07-03 15:29:10
【问题描述】:

我有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();

客户端/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”。
我尝试显示每个客户已支付的总金额。请帮忙。

【问题讨论】:

    标签: mysql laravel laravel-query-builder


    【解决方案1】:

    使用withCount() 方法:

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

    如果您想在不实际加载关系的情况下计算关系结果的数量,您可以使用withCount 方法,该方法将在结果模型上放置一个{relation}_count 列。

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2018-08-27
      • 2018-01-15
      • 2017-06-23
      相关资源
      最近更新 更多