2016-12-25 49 views
2

我有这样的关系:如何统计有多少物品属于哪个类别?

文章

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所有类别

+0

你的问题不清楚。你能举一些例子吗? –

+0

我编辑了我的问题 – uzhas

+0

你的问题仍然没有任何意义。你能举一些你需要的例子吗? –

回答

4

Category模型定义hasMany关系的数:

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 
0

使用withCount()方法来算的关系。

Model::where('id', $id)->withCount('relation')->first(); 

如果你要计算从一个关系结果的数量,而无需实际加载它们,你可以使用withCount方法,这将放置{relation}_count列上你的最终模型。

+0

我编辑我的问题... – uzhas

0

我认为你应该使用group by语句。 您选择CATEGORY_ID,COUNT(*)FROM文章GROUP BY CATEGORY_ID 这将返回的每个物品CATEGORY_ID

相关问题