Php 显示下方帖子的主要类别
PostController.phpPhp 显示下方帖子的主要类别,php,laravel,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
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>
@foreach($categories作为$category)
{{$category->category_name}
@foreach($posts\u list作为$post\u list)
@endforeach
@endforeach
我们的想法是这样的:
类别
- 职位
- 职位
- 职位
- 职位
- 职位
我目前的解决方案是可行的,但我可以看到这很快成为一个需要维护的问题 您需要将关系添加到模型中 提供一对多的关系,您可以执行以下操作 在您的类别模型中
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>
@foreach($categories作为$category)
{{$category->category_name}
@foreach($category->posts as$post)
@endforeach
@endforeach
我还认为这条线路不是最好的方式,你可能需要申请一条线路
<a href="{{ $post->post_id}}">
你的问题是什么?如果一切正常,我们能提供什么帮助?帖子可以有多个类别吗?从MVC的术语开始,这在概念上是错误的,因为您在视图中的一个绝对不属于它的地方进行数据库查询。