更新
我有一个包含所有类别的视图,通过单击一个类别,用户可以转到该类别。但如果没有这一类的帖子,我想避免去那里。我试着这样做:
@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);
}
但是它不起作用。所有的类别都写在"帖子没有类别"或";Open"。也就是说,检查不能正常工作。
在您的刀片文件检查条件
@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);
}
在控制器中你可以做
$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()
}