我有以下查询:
@php
$age_id = \App\Goalage::where('goal_id',$cat_fil->id)->pluck('age_id');
$age_name = \App\Age::wherein('rangeid',$age_id)->groupby('rangeid')->get();
@endphp
以及以下If条件和foreach:
@if(count($age_name) > 4 )
@foreach($age_name as $agename)
<button type="button" class="btn btn-outline-primary btn-sm-new mr-1">
{{$agename->agerange}} yrs
</button>
@endforeach
<a href="{{some.route}}">Click here for more than 4 results <a>
@else
//same code but will show 4 results or less
@endif
如何更改以下语法,以便即使有更多结果,也只能在foreach中循环/显示前4个结果?
@foreach($age_name as $agename)
答案 0 :(得分:2)
您可以执行以下操作以在4次迭代后中断循环
在foreach
循环中添加
@if($loop->iteration > 4)
@break
@endif
您也可以针对Laravel 5.2进行此操作
@php
$count = 0;
@endphp
@foreach($age_name as $agename)
@if($count >= 4 )
@break
@endif
<button type="button" class="btn btn-outline-primary btn-sm-new mr-1">
{{$agename->agerange}} yrs
</button>
@php
$count++;
@endphp
@endforeach
答案 1 :(得分:0)
使用CrawlerProcess
或take()
从查询中提取一定数量的记录:
limit()
或
$age_name = \App\Age::wherein('rangeid',$age_id)->groupby('rangeid')->take(4)->get();
编辑:
使用$age_name = \App\Age::wherein('rangeid',$age_id)->groupby('rangeid')->limit(4)->get();
获取循环的当前迭代,并在达到某个迭代(在您的情况下为 4 )时中断。
$loop->iteration