dpv21589 2015-08-27 11:43
浏览 218
已采纳

Laravel 5如何在循环中进行循环

How can i make loop like this in laravel?

I have category and posts table ,
on posts table there is field for category id.

And some categories has no post , so i dont want to show empty categories on my view..

Sorry for my english . I hope you understand me

Loop:Category {

$categoryname

Loop:PostsBelongsToCategory {

$postTitle

}
}

I want to print it to page like this :

Category 1 :

Category 1 Post A ,

Category 1 Post B ,

Category 1 Post C ,

Category 2 :

Category 2 Post A ,

Category 2 Post B ,

Category 2 Post C ,

  • 写回答

1条回答 默认 最新

  • dongluojiao6322 2015-08-27 12:24
    关注

    Setup your relations between the categories and posts table.

    $categories = App\Categroy::with('posts')->get();
    
    foreach($categories as $category) {
        echo $category->name;
        foreach($category->posts as $post) {
            echo $category->name.' '.$post->title.',';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?