2016-10-12 3 views
1

以下の関係があります。 User->hasMany(Posts)およびUser->belongsToMany(Following)。 今、私は以下を取得したいと思います。特定のタイプのpostを持つ、次のユーザーをすべて取得します。私はこれまでに来ていますLaravel count結果の件数は、からです。

これはいいです、少なくとも1つの記事タイプ投稿を持つユーザーのみを返します。どのような私がここに欲しいの記事どのように多くの彼のポストのカウントを含めるには対応してまでも

{ 
    "id": 37, 
    "name": "Telis Xrysos", 
    "email": "[email protected]", 
    "url": "", 
    "personal_quote": "", 
    "profile_image_url": "/assets/images/user-no-image.jpg", 
    "private": "0", 
    "posts": [ 
     { 
     "id": 238, 
     "description": "This is Tony Montana #Tony #Montana", 
     "source": "Tony Montana Quote", 
     "image_url": null, 
     "type": "article", 
     "likes": 0, 
     "comments": 0, 
     "user_id": 37, 
     "created_at": "2016-10-11 16:26:28" 
     } 
    ] 
    } 

です。私は後でposts属性でカウントを行うことができますが、これは一時的なものであり、後で削除されます。

私はこれを試してみましたが、私が得るすべては、各ユーザーarticles_count = []

public function articlesCount() 
    { 
     return $this->posts()->selectRaw('id, count(*) as aggregate')->where('type','article')->groupBy('id'); 
    } 

$writers = $user 
      ->following() 
      ->with('posts') 
      ->with('articlesCount') 
      ->whereHas('posts' ,function($query){ 
       $query->where('type','article'); 
      }) 
      ->get(); 
+0

[link](http://laravel.io/forum/05-03-2014-eloquent-get-count-relation)が役立ちます。 – Maraboc

答えて

0

のための余分な属性であり、私は単純に雄弁

protected $appends = ['ArticleCount']; 
    public function getArticleCountAttribute(){ 
    return $this->posts->count(); 
    } 

でカスタム属性は関係を忘れないように入れています

public function posts(){ 
    return $this->hasMany('app\posts','id_user','id'); 
} 
+0

もう1つ。これにより、ユーザオブジェクト内のポストも読み込まれます。カウントを取得するにはどうすればよいですか? – LefterisL

+0

は 'makeHidden( 'posts')'を使っていましたが、それが最高のオプションであるかどうかわかりません。 – LefterisL

+0

'$ this-> posts() - > count()'がより良いオプションになるはずです – Skysplit

関連する問題