larave:当计数达到给定值时如何从 foreach 循环中删除选定的数据

问题描述

概览

我正在使用预约预订系统,但时间段对所有人开放 没有预订限制 我想在所选时间段的预订计数达到 25 时隐藏/禁用所选时间段

这是我用于 foreach 的变量

@PHP
$times = DB::table('times')
->where('app_id',$app->id)
->get();
@endPHP

我就是这样的

@foreach ($times as $item)
@PHP

$blocktime = DB::table('bookings')->where('app_id',$app->id)
->where('time',$item->time)
->where('status',1)->get();
@endPHP

<div class="col-md-3" style="padding-bottom: 10px;">
                                            
<label class="btn btn-outline-primary">
<input type="radio" name="time" value="{{ $item->time }}">
<span>{{ $item->time }}</span>
</label>

</div>
@endforeach

在这个变量 $blocktime 中,我计算在什么时候为选定的时间段进行了多少预订

$blocktime  == 25 

$blocktime 计数达到 25 时,我想禁用该特定时间段,我该怎么做?

感谢您的宝贵时间

解决方法

从我从你的问题中得到的信息来看,你需要不显示 time 已经有 25 booking

您只需要使用 count() 而不是 get(),然后如果大于 24 则使用 continue

@foreach ($times as $item)
@php

$blocktime = DB::table('bookings')->where('app_id',$app->id)
->where('time',$item->time)
->where('status',1)->count();

if ($blocktime > 24) {
    continue;
}
@endphp

<div ....>
</div>
@endforeach

我还没有测试代码,希望它有效。

,

根据我对您的查询的理解,如果 $blocktime = 25,您想禁用包含时间段的单选按钮,因此您可以执行以下操作来实现此目的:

    @foreach ($times as $item)
    @php
    $breakTime = false;
    $blocktime = DB::table('bookings')->where('app_id',$app->id)
    ->where('time',$item->time)
    ->where('status',1)->count();
    if ($blocktime == 25) {
        $breakTime = true;
        continue;
    }
    @endphp
    
    
    <div class="col-md-3" style="padding-bottom: 10px;">
                                                
    <label class="btn btn-outline-primary">
    <input type="radio" name="time" value="{{ $item->time }}" {{($breakTime == true) ? 'disable' : ''}}> 
    <span>{{ $item->time }}</span>
    </label>
    
    </div>
    @endforeach