2016-03-07 146 views
11

我在我的web应用程序Laravel得到这个:Laravel支票托收是空

@foreach($mentors as $mentor) 
    @foreach($mentor->intern as $intern) 
     <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}"> 
      <td>{{ $intern->employee->FirstName }}</td> 
      <td>{{ $intern->employee->LastName }}</td> 
     </tr> 
    @endforeach 
@endforeach 

我怎么能检查是否有任何$mentors->intern->employee

当我这样做:

@if(count($mentors)) 

它不检查这一点。

回答

8

您可以随时统计收藏。例如$mentor->intern->count()将返回导师有多少实习生。

https://laravel.com/docs/5.2/collections#method-count

在你的代码,你可以做这样的事情

foreach($mentors as $mentor) 
    @if($mentor->intern->count() > 0) 
    @foreach($mentor->intern as $intern) 
     <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}"> 
      <td>{{ $intern->employee->FirstName }}</td> 
      <td>{{ $intern->employee->LastName }}</td> 
     </tr> 
    @endforeach 
    @else 
     Mentor don't have any intern 
    @endif 
@endforeach 
21

要确定是否有您可以执行以下的任何结果:

if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { } 
if ($mentor->count()) { } 
if (count($mentor)) { } 

备注/参考

->first()

http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty()http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors)作品,因为集合实现可数和内部计数()方法:

http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_count

所以你可以做的是:

if (!$mentors->intern->employee->isEmpty()) { } 
+0

是的,我知道,但导师并不总是有一个实习生。那我该如何检查? – Jamie

4

这是最快的方法:

if ($coll->isEmpty()) {...} 

count其他解决方案做的比你需要多一点这花费更多时间。

另外,isEmpty()的名字相当准确地描述了你想要在那里检查的内容,这样你的代码将更具可读性。