猿问

如何知道 foreach (刀片模板)上是否没有打印任何内容

我的 laravel 视图中有 2 个嵌套循环


@foreach ($clubs as $club)

<div class="jumbotron text-center">

<h1>{{$club->nom}}</h1>

</div>


<div class="container">

<div class="row">

    <div class="col-sm-12">

        <h3>Grupos</h3>

        @foreach ($grupos as $grupo)

            @if ($grupo->club == $club->id)

                <p>

                    <strong>Nombre: </strong> {{$grupo->nom}} <br>

                    <strong>Tipo: </strong> Grupo de {{$grupo->tipo}} <br>

                    <strong>Horario disponible: </strong> {{$grupo->dia}}, {{$grupo->horario}} <br>

                </p>

            @endif

        @endforeach

    </div>

    </div>

</div>


@endforeach

$grupos 是一个包含我的组表中所有组的数组,我遍历整个内容并仅在外键俱乐部等于当前正在迭代的当前俱乐部时打印信息。如果没有,则不会打印任何信息,但我想打印一条消息,表明在该迭代期间没有打印任何内容,有什么办法可以做到吗?


这是我想要的输出的一个例子


id 为 1 的俱乐部 A 有 5 个组


id 为 2 的俱乐部 B 有 0 个组


------ 俱乐部 A --------


第 1 组


第 2 组


第 3 组


第 4 组


第 5 组


------- 俱乐部 B -------


该俱乐部没有团体


慕姐8265434
浏览 101回答 1
1回答

MMTTMM

你需要一些关系来实现这一点。在这一点上,$grupos所有俱乐部都是一样的。以下是您的最小表结构应该如何:俱乐部id (BIGINT 20)name (VARCHAR 255)团体id (BIGINT 20)name (VARCHAR 255)club_id (BIGINT 20)现在您可以设置模型:俱乐部.php<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Club extends Model{&nbsp; &nbsp; protected $table = 'clubs';&nbsp; &nbsp; public function groups () {&nbsp; &nbsp; &nbsp; &nbsp; return $this->hasMany(Group::class);&nbsp; &nbsp; }}组.php<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Group extends Model{&nbsp; &nbsp; protected $table = 'groups';&nbsp; &nbsp; public function club () {&nbsp; &nbsp; &nbsp; &nbsp; return $this->belongsTo(Club::class);&nbsp; &nbsp; }}现在,在您加载视图的控制器中,您可以获取所有数据并将其传递:俱乐部控制器.php<?phpnamespace App\Http\Controllers;use App\Club;use Illuminate\Http\Request;class ClubController extends Controller{&nbsp; &nbsp; public function index (Request $request) {&nbsp; &nbsp; &nbsp; &nbsp; $clubs = Club::with('groups')->get();&nbsp; &nbsp; &nbsp; &nbsp; return view('clubs', ['clubs' => $clubs]);&nbsp; &nbsp; }}现在,在您的视图中显示俱乐部:俱乐部.blade.php@foreach($clubs as $club)&nbsp; &nbsp; <h1>Club: {{ $club->name }}</h1>&nbsp; &nbsp; @if($club->groups)&nbsp; &nbsp; &nbsp; &nbsp; <h2>Groups:</h2>&nbsp; &nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @foreach($club->groups as $group)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>{{ $group->name }}</li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; @else&nbsp; &nbsp; &nbsp; &nbsp; <h2>This club has no groups.</h2>&nbsp; &nbsp; @endif&nbsp; &nbsp; <br>@endforeach我希望这对您有所帮助,并让您更好地了解如何在 Laravel 中使用关系 :)
随时随地看视频慕课网APP
我要回答