主类别显示下方的帖子

时间:2019-04-10 10:29:28

标签: php laravel

PostController.php

public function index($id) 
{
    $post = Post::where('post_id', $id)->first();

    $categories = DB::table('categories')->select('name AS category_name', 'slug AS category_slug', 'category_id AS cid')->get();

    return view('post', compact('post','categories'));
}

post.blade.php

<div class="accordion sticky-top" id="sideNavigation" style="top:55px">
    @foreach($categories as $category)
        <?php $posts_list = DB::table('posts')->join('categories', 'categories.category_id', 'posts.category_id')
            ->where('posts.category_id', $category->cid)
            ->get();
        ?>
        <h2 class="mb-0 border-bottom py-2 ">
            <button class="btn btn-link" type="button" data-toggle="collapse"
                    data-target="#{{$category->category_slug}}" aria-expanded="true"
                    aria-controls="{{$category->category_slug}}">
                {{ $category->category_name}}
            </button>
        </h2>

        <div id="{{$category->category_slug}}" class="collapse" aria-labelledby="headingOne"
             data-parent="#sideNavigation">
            <div class="card-body">
                <ul class="list-unstyled">
                    @foreach($posts_list as $post_list)
                        <li><a href="{{ $post_list->post_id}}">{{$post_list->title}}</a></li>
                    @endforeach
                </ul>
            </div>
        </div>
    @endforeach
</div>

想法是这样的:

类别

  • 发布
  • 发布
  • 发布

类别2

  • 发布
  • 发布

我当前的解决方案有效,但是我可以很快看到这成为维护问题。

1 个答案:

答案 0 :(得分:0)

您需要向模型添加关系。 Documentation is here

提供一对多关系,您可以执行以下操作

在您的类别模型中

public function posts()
{
    return $this->hasMany('App\Post', 'category_id', 'category_id');
}

在您的帖子模型中

public function category()
{
    return $this->hasOne('App\Category', 'category_id', 'category_id');
}

然后您可以清理视图

<div class="accordion sticky-top" id="sideNavigation" style="top:55px">
    @foreach($categories as $category)
       <h2 class="mb-0 border-bottom py-2 ">
       <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#{{$category->category_slug}}" aria-expanded="true" aria-controls="{{$category->category_slug}}">{{ $category->category_name}}</button>
       </h2>
       <div id="{{$category->category_slug}}" class="collapse" aria-labelledby="headingOne" data-parent="#sideNavigation">
           <div class="card-body">
               <ul class="list-unstyled">   
               @foreach($category->posts as $post)
                   <li><a href="{{ $post->post_id}}">{{$post->title}}</a></li>
               @endforeach
               </ul>
           </div>
       </div>
   @endforeach     
</div>

我还认为这不是最好的解决方法,您可能需要一条路线申请

<a href="{{ $post->post_id}}">