Laravel 如何计算有多少篇文章属于哪一类?
我有这样的关系: 文章Laravel 如何计算有多少篇文章属于哪一类?,laravel,laravel-5,laravel-5.2,Laravel,Laravel 5,Laravel 5.2,我有这样的关系: 文章 public function category() { return $this->belongsTo('App\Models\Categories'); } 类别有翻译 public function c_translations() { return $this->hasMany('App\Models\CategoryTranslations', 'category_id'); } 在文章中我有类别id
public function category()
{
return $this->belongsTo('App\Models\Categories');
}
类别有翻译
public function c_translations()
{
return $this->hasMany('App\Models\CategoryTranslations', 'category_id');
}
在文章中我有类别id,在翻译中我也有类别id。所以我如何计算每个类别有多少篇文章。有什么建议吗
$articles = Articles::all();
foreach($articles as $article ){
$articles_category = Articles::where('id',$article->id)->withCount('category')->first();
}
我尝试了这个方法,但所有类别的结果都是0。使用方法计算关系
Model::where('id', $id)->withCount('relation')->first();
如果您想在不实际加载的情况下计算关系中的结果数,可以使用withCount
方法,该方法将在结果模型上放置{relation}\u count
列
我认为你应该使用分组对账单。 您可以按类别id从文章组中选择类别id、计数(*) 这将返回每个类别id的文章数在您的
类别
模型中定义一个关系,如下所示:
public function articles()
{
return $this->hasMany('App\Models\Article');
}
然后您可以使用来查询它,如下所示:
$categories = Category::withCount('articles')->get();
将其传递到您的视图,然后您可以访问以下类别的文章数量:
@foreach ($categories as $category)
<li>{{ category->title }}</li>
<li>{{ category->articles_count }}</li>
@endforeach
@foreach($categories作为$category)
{{类别->标题}
{{category->articles_count}
@endforeach
你的问题仍然毫无意义。你能给出一些你需要的例子吗?我想显示数据库中的所有类别,以及这些类别的文章数量