首页 > 解决方案 > 如何在刀片中执行嵌套的 foreach 循环?

问题描述

我想显示 Laravel Blade 中的主题以及该主题下每个主题中教授的相关主题。我怎么能在 Laravel 8 中做到这一点。

这是我的模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class topic extends Model
{
    use HasFactory;
    protected $table='topics';
    protected $primaryKey='id';
    protected $fillable=['author_id', 'course_id', 'url', 'topic', 'powerpoint', 'description', 'views'];

public function author(){
    return $this->belongsTo(author::class);
}

public function course(){
    return $this->belongsTo(course::class);
}
}

这是我的控制器:

public function courses(){

    $topics = topic::join('authors', 'topics.author_id', '=', 'authors.id')
    ->join('courses', 'topics.course_id', '=', 'courses.id')
    ->select('topics.*', 'authors.first_name', 'authors.last_name', 'courses.course')
    ->get();

    $topicsCounter = topic::join('authors', 'topics.author_id', '=', 'authors.id')
    ->join('courses', 'topics.course_id', '=', 'courses.id')
    ->count();

    return view('courses', compact('topics', 'topicsCounter'));
}

这是我的刀片:

@foreach($topics as $topic)

    {{ $topic->course }} :
//here is where i want to list all the topic found in this specific course

    @endforeach

这是正确的方式还是我应该以另一种更好的方式来做?

标签: laravel

解决方案


使用外部组件接受 $course 作为参数,然后将其包含在主刀片中。


推荐阅读