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

Checking for the presence of posts in a category does not work. php, Blade, Laravel

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

@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() 是我的类别模型中的 eloquent 关系:

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

但是没用。所有类别都写为“post 没有类别”或“开放”。也就是说,检查无法正常工作。

在控制器中你可以做

$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() 
}

在你的 blade 文件中这样检查条件

@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);
}