简体   繁体   中英

Laravel count # of results from whereHas

I have the below relationship. User->hasMany(Posts) and 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 . 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. 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.

I have tried this but all i get is an extra attribute for each user 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

  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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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