我有这种关系:
文章
public function category()
{
return $this->belongsTo('App\Models\Categories');
}
类别有翻译
public function c_translations()
{
return $this->hasMany('App\Models\CategoryTranslations', 'category_id');
}
在文章中,我有类别ID,在翻译中,我有category_id。因此,我该如何计算每个类别有多少篇文章。有什么建议吗?
$articles = Articles::all();
foreach($articles as $article ){
$articles_category = Articles::where('id',$article->id)->withCount('category')->first();
}
我试过了,但所有类别总得0
hasMany
在Category
模型中将关系定义为:
public function articles()
{
return $this->hasMany('App\Models\Article');
}
然后,您可以使用withCount
以下查询它:
$categories = Category::withCount('articles')->get();
将其传递到您的视图,然后您可以访问“否”。的文章类别为:
@foreach ($categories as $category)
<li>{{ category->title }}</li>
<li>{{ category->articles_count }}</li>
@endforeach
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句