[英]Laravel - How to display all posts related to category
我必须在帖子中创建类别,但我有一个错误:
试图获取非对象的属性“id”(查看:C:\xampp\htdocs\klikdesaku\resources\views\home.blade.php)
如果我单击类别,我想显示与类别相关的所有帖子
这是我的 model Post.php:
public function category(){
return $this->belongsTo(Category::class);
}
类别.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>
因为Category
与Post
有 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
如果您的应用程序很大,您将不得不使用嵌套循环,这不是最好的主意,但对于一个小项目,它会完成这项工作。
@foreach($categories as $category)
@foreach($category->posts as $post)
<ul>
<li>
<a href="{{ $post->id }}">{{ $category->name }}</a>
</li>
</ul>
@endforeach
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.