0

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

@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()在我的类别模型中是一个雄辩的关系:

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

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

4

2 回答 2

2

在你的刀片文件检查条件中

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

如果未添加,则在您的类别模型中添加关系(一对多

public function posts(){
    return $this->hasMany(Post::class);
}
于 2021-01-22T06:21:12.110 回答
1

在控制器中你可以做

$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() 
}
于 2021-01-22T06:08:54.773 回答