繁体   English   中英

Laravel计算fromHas的结果数量

[英]Laravel count # of results from whereHas

我有以下关系。 User->hasMany(Posts)User->belongsToMany(Following) 现在我想检索以下内容。 获取具有特定类型post用户的所有以下用户。 我到目前为止

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

哪个好,只返回至少有1个文章类型的用户帖子。 我想要的是在回复中

{
    "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"
      }
    ]
  }

包括他的帖子中有多少是文章的计数。 我可以在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();

我只是在Eloquent中添加了一个自定义属性

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

不要忘记这段关系:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM