繁体   English   中英

检查某个类别中是否存在帖子不起作用。 php,刀片,Laravel

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

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

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

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

在您的 controller 中使用withCount方法

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

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

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

在 controller 你可以做

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM