以下の関係があります。 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();
[link](http://laravel.io/forum/05-03-2014-eloquent-get-count-relation)が役立ちます。 – Maraboc