我在Laravel webapp中得到了这个:
@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))
它没有检查。
您可以随时统计该集合。例如,$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
要确定是否有任何结果,您可以执行以下任何操作:
if ($mentor->first()) { }
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }
备注/参考
->first()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first
isEmpty()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty
->count()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count
count($mentors)
的工作原理是因为Collection实现了Countable和一个内部count()方法:
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count
isNotEmpty()
https://laravel.com/docs/5.7/collections#method-isnotempty
所以你能做的是:
if (!$mentors->intern->employee->isEmpty()) { }
从Laravel 5.3开始,您可以简单地使用:
if ($mentor->isNotEmpty()) {
//do something.
}
文档https://laravel.com/docs/5.5/collections#method-isnotempty
这是最快的方法:
if ($coll->isEmpty()) {...}
像count
这样的其他解决方案比你需要的更多,这需要花费更多的时间。
此外,isEmpty()
名称非常精确地描述了您要检查的内容,因此您的代码将更具可读性。
我更喜欢
(!$mentor)
更有效和准确
从php7
你可以使用Null Coalesce Opperator:
$employee = $mentors->intern ?? $mentors->intern->employee
这将返回Null
或员工。