在Laravel中获取与类别相关的帖子

时间:2020-03-04 09:51:15

标签: php laravel laravel-6

我有一个类别表,一个发布表和一个表,该表显示了发布和类别之间的关系,即Categories_Posts

**Posts**
id | title | text

**Categories_Posts**
category_id | post_id

**Category**
id | name

我有音乐,新闻,视频等类别。

模型

class Post extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class, 'categories_posts');
    }
}

class Category extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class, 'categories_posts');
    }
}

如何在侧边栏显示与每个类别相关的帖子

我做到了

@foreach($posts as $post)
    <div> {{ $post->subject }}</div>
    <div> {{ $post->image }}</div>
    @foreach($post->categories as $category)
        <div> {{ $category->name}}</div>
    @endforeach
@endforeach

它在侧边栏中显示每个类别的所有帖子,但是我在侧边栏中有一个地方只想显示视频帖子,在侧边栏中有一个地方我想只显示音乐帖子等等。

我该怎么做?

希望你能理解我

1 个答案:

答案 0 :(得分:0)

您可以使用with()方法。

$data = Post::with('categories')->get();

您认为:

@foreach($data as $post) // will loop over posts and show title
    <div>{{$post->title }} </div>
    @foreach($post->categories as $category)
         <div> {{ $category->name}} </div>
    @endforeach
@endforeach