Laravel blade 中的 count() "where" 语句?

count() "where" statement in Laravel blade?

我对在我的应用程序中显示电子邮件统计信息的快速计数很感兴趣,但我对寻找一种生成计数的有效方法感到困惑。我希望只使用 eloquent 关系与 blade.

中的某种 "count where" 语句

获取总计数正常工作:

{{count($emails->mandrillemails)}}

但是这样的事情可能吗?:

{{count($emails->mandrillemails->msg_state == 'bounced')}}
{{count($emails->mandrillemails->msg_state == 'open')}}

这是我的带有@if 和@foreach 语句的代码块:

     @if(count($sentEmails) > 0)
      @foreach ($sentEmails as $emails)
       <tr>
        <td>
          @if(count($emails->mandrillemails) > 0)
             <p><span class="badge"><i class="fa fa-paper-plane"></i> {{count($emails->mandrillemails)}}</span> <span class="badge"><i class="fa fa-exclamation-triangle"></i> {{count($emails->mandrillemails->msg_state == 'bounced')}}</span></p>
          @endif
        </td>
      </tr>

当我尝试这样做时,我在 "msg_state"

上收到未定义的 属性 错误

$emails->mandrillemails()->whereMsgState('bounced')->count() 应该可以。

你可以这样算一段关系:

$emails->mandrillemails()->whereMsgState('bounced')->count();

由于您正在 @foreach 处理事情,您可能希望预先加载此数据。当您对关系进行计数时,这会稍微复杂一些 - 请参阅 http://laravel.io/forum/05-03-2014-eloquent-get-count-relation and http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/ 了解一些可能的技术来预先加载计数值而不是相关项目的整个列表。