php 嵌套foreach循环重复行(Laravel 9)

aoyhnmkz  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(185)

我目前正在用Laravel 9开发我的第一个真实的的项目。我遇到了一个无法解决的问题。我有两个表Categories和Articles,它们与字段id(categories表)和category_id(articles表)相连。
在我的类别控制器中:

public function categories(){
                            $categories = Category::all();
                            $articles = Article::all();
                           return view('category.categories')->with('cats',$categories)->with('arts',$articles);
             }

我的Blade视图设置如下:

<ul>
            @foreach($cats as $cat)
             <li>{{ $cat->name}}
              <ul>
              @foreach($arts as $art)
              @if($cat->id == $art->category_id)
             <li>{{ $art->title }}</li>
              @else
              <li>No articles</li> 
            @endif
            @endforeach
           </ul>
          </li>
          @endforeach

当我登记入住的时候我收到了这个

Category 1
            Article title 1
            No articles
            No articles
            No articles
            No articles
            Category 2
            No articles
            Article title 2
            No articles
            No articles
            No articles
            Category 3
            No articles
            No articles
            Article title 3
            No articles
            No articles
            Category 4
            No articles
            No articles
            No articles
            Article title 4
            No articles
            Category 5
            No articles
            No articles
            No articles
            No articles
            No articles

我怎样才能解决这个问题,所以它只说一次没有文章下类别5

6kkfgxo0

6kkfgxo01#

我会确保你们在模特中的关系都建立好了。
在类别模型中:

public function articles()
{
    return $this->hasMany(Article::class);
}

然后,在您的CategoryController中:

public function categories(){
    $categories = Category::with('articles')->get();
    return view('category.categories')->with('cats',$categories);
}

我不太确定刀片部分,但您应该能够做到:

<ul>
  @foreach($cats as $cat)
    <li>{{ $cat->name}}</li>
    @if(empty($cat->articles))
      <li>No articles</li> 
    @else
      <ul>
        @foreach($cat->articles as $art)
          <li>{{ $art->title }}</li>
        @endforeach
      </ul>
    @endif
  @endforeach
</ul>

相关问题