为 laravel 中的博客类别创建计数器
create counter for blog categories in laravel
我打算为我的博客类别创建一个计数器。这应该出现在我的类别的名称右侧。我使用带有变量附加的模型,之后我将在我的 blade 中使用以在一个跨度内显示我的结果。但我不太清楚如何在我的模型中使用计数。我在我的模型博客中这样做。
我的变量附加包含:
protected $appends = [
'custom_fields',
'has_media',
'restaurant',
'blog_category',
'viewer',
'postCounter',
];
我正在处理这个:
return $this->blogs()->count();
我在博客和 blog_category 之间有关系:
public function blogCategory()
{
return $this->belongsTo(\App\Models\BlogCategory::class, 'blog_category_id', 'id');
}
我想做的在我看来出现例如:
innovation (2)
在我看来,我正在这样做:
@foreach($categories as $category)
<li><a href="{{ url('blogs/'.$category->name) }}">{{ trans('web.blog_category_'.$category->name) }}</a><span>{{$category->postCounter}}</span></li>
@endforeach
但总是返回 0,我有 post 类别
已更新
使用 laravel relationship withCount
您可以轻松做到这一点。如果你想计算一个关系的结果数量而不实际加载它们,你可以使用 withCount 方法,它会在你的结果模型上放置一个 {relation}_count
列。
将 withCount
方法添加到您的查询中
$categories = Category::withCount('blogCategory')->get();
您可以在 foreach 循环中访问计数
// $category->blogCategory_count
@foreach($categories as $category)
<li>
<a href="{{ url('blogs/'.$category->name) }}">
{{trans('web.blog_category_'.$category->name) }}
</a>
<span>{{$category->blogCategory_count}}</span>
</li>
@endforeach
我打算为我的博客类别创建一个计数器。这应该出现在我的类别的名称右侧。我使用带有变量附加的模型,之后我将在我的 blade 中使用以在一个跨度内显示我的结果。但我不太清楚如何在我的模型中使用计数。我在我的模型博客中这样做。
我的变量附加包含:
protected $appends = [
'custom_fields',
'has_media',
'restaurant',
'blog_category',
'viewer',
'postCounter',
];
我正在处理这个:
return $this->blogs()->count();
我在博客和 blog_category 之间有关系:
public function blogCategory()
{
return $this->belongsTo(\App\Models\BlogCategory::class, 'blog_category_id', 'id');
}
我想做的在我看来出现例如:
innovation (2)
在我看来,我正在这样做:
@foreach($categories as $category)
<li><a href="{{ url('blogs/'.$category->name) }}">{{ trans('web.blog_category_'.$category->name) }}</a><span>{{$category->postCounter}}</span></li>
@endforeach
但总是返回 0,我有 post 类别
已更新
使用 laravel relationship withCount
您可以轻松做到这一点。如果你想计算一个关系的结果数量而不实际加载它们,你可以使用 withCount 方法,它会在你的结果模型上放置一个 {relation}_count
列。
将 withCount
方法添加到您的查询中
$categories = Category::withCount('blogCategory')->get();
您可以在 foreach 循环中访问计数
// $category->blogCategory_count
@foreach($categories as $category)
<li>
<a href="{{ url('blogs/'.$category->name) }}">
{{trans('web.blog_category_'.$category->name) }}
</a>
<span>{{$category->blogCategory_count}}</span>
</li>
@endforeach