[英]Laravel count # of results from whereHas
I have the below relationship. 我有以下关系。 User->hasMany(Posts)
and User->belongsToMany(Following)
. User->hasMany(Posts)
和User->belongsToMany(Following)
。 Now i want to retrieve the following. 现在我想检索以下内容。 Get all the following users of a user that have a specific type of post
. 获取具有特定类型post
用户的所有以下用户。 I have come so far 我到目前为止
$writers = $user
->following()
->with('posts')
->whereHas('posts' ,function($query){
$query->where('type','article');
})
->get();
Which is ok and returns only the Users that have at least 1 article type post. 哪个好,只返回至少有1个文章类型的用户帖子。 What i want here is to also in the response 我想要的是在回复中
{
"id": 37,
"name": "Telis Xrysos",
"email": "txrysos@mail.com",
"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"
}
]
}
To include a count of how many of his posts are articles. 包括他的帖子中有多少是文章的计数。 I could do a count afterwards at the posts
attribute although that is just temporary and will be removed afterwards. 我可以在posts
属性后进行计数,虽然这只是暂时的,之后会被删除。
I have tried this but all i get is an extra attribute for each user articles_count = []
我试过这个,但我得到的是每个用户的额外属性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();
i'm simply put a custom attribute in Eloquent 我只是在Eloquent中添加了一个自定义属性
protected $appends = ['ArticleCount'];
public function getArticleCountAttribute(){
return $this->posts->count();
}
don't forget the relationship too : 不要忘记这段关系:
public function posts(){
return $this->hasMany('app\posts','id_user','id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.