检查类别中是否存在帖子不起作用 php、刀片、Laravel

问题描述

我有一个包含所有类别的视图,通过单击一个类别,用户可以转到该类别。但如果该类别中没有帖子,我想阻止去那里。我试图这样做:

@if(($category->id === $category->posts()) !== 0)
   <a class="btn btn-success" href="{{ route('category',$category->code)}}">Open</a>
@else
   <span class="btn btn-warning">No posts in this category</span>
@endif

posts() 在我的 Category 模型中是一个雄辩的关系:

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

但它不起作用。所有类别都写有“帖子没有类别”或“打开”。也就是说,检查不能正常工作。

解决方法

在你的刀片文件中检查这样的情况

@if($category->posts_count > 0)
   <a class="btn btn-success" href="{{ route('category',$category->code)}}">Open</a>
@else
   <span class="btn btn-warning">No posts in this category</span>
@endif

在您的控制器中使用了 withCount 方法

$category = Category::withCount('posts')->get();

并在您的类别模型中添加关系(如果未添加)(one to many)

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

在控制器中你可以做

$category = Category::withCount('posts')->get()

它生成 post_count 密钥,您可以在视图中查看

@if($category->posts_count > 0)
   <a class="btn btn-success" href="{{ route('category',$category->code)}}">Open</a>
@else
   <span class="btn btn-warning">No posts in this category</span>
@endif

https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models


更新

$category = Category::withCount('posts')->findOrFail(1)

if($category->posts_count > 1){
   return redirect()->back() 
}