Laravel - 如何显示与类别相关的所有帖子

时间:2021-03-02 01:44:39

标签: php laravel laravel-8

我必须在帖子中创建类别,但我有一个错误:

<块引用>

试图获取非对象的属性“id”(视图:C:\xampp\htdocs\klikdesaku\resources\views\home.blade.php)

如果我点击类别,我想显示与类别相关的所有帖子

这是我的模型Post.php:

public function category(){
   return $this->belongsTo(Category::class);
}

Category.php:

public function posts(){
    return $this->hasMany(Post::class, 'category_id', 'id');
}

home.blade.php:

<h5 class="card-header">Categories</h5>
  <div class="card-body">
    <div class="row">              
        @foreach($categories as $category)
        <div class="col-lg-6">
          <ul class="list-unstyled mb-0">
            <li>
             <a href="{{$category->post->id}}">{{$category->name}}</a>
            </li>
          </ul>
        </div>
        @endforeach
    </div>
  </div>

2 个答案:

答案 0 :(得分:1)

因为 CategoryPost 有 hasMany 关系,所以你必须先获取帖子,然后获取帖子的数据。像这样的东西。

$categories = Category::with('posts')->get();

@foreach($categories as $category)
    @foreach($category->posts as $post)
        <ul>
            <li>
                <a href="{{ $post->id }}">{{ $post->title }}</a>
            </li>
        </ul>
    @endforeach
@endforeach

答案 1 :(得分:0)

如果你的应用很大,你将不得不使用嵌套循环,这不是最好的主意,但对于一个小项目,它可以完成这项工作。

@foreach($categories as $category)
    @foreach($category->posts as $post)
        <ul>
            <li>
                <a href="{{ $post->id }}">{{ $category->name }}</a>
            </li>
        </ul>
    @endforeach
@endforeach