简体   繁体   中英

Count by categories in Laravel eloquent relationships in model rather than query builder

I have post Model which has multiple reactions (Like, dislike etc)

I want to count those reaction by their attr_id. I tried below code and it gives total number of reactions on post.

public function PostReaction() {
        return $this->hasMany('App\PostReaction');
    }

public function getAttributesCountAttribute() {
        return $this->PostReaction()->count();
}

and if I do

return $this->PostReaction()->groupBy('attr_id')->count();

It returns only first reaction count instead of all. It should give array of count with all reactions

I think that you have this error because $this->PostReaction returns the reactions of all posts.

Try to call the function outside the model by making a repository class where you'll have the method getAttributesCountAttribute and pass to it the $post on which you want to count the reactions. Something like:

public function getAttributesCountAttribute($post) {
        return $post->PostReaction->count();
}

Same thing if there is multiple posts, try to loop for each post and get its reactions not all at once.

I solved it by using below code

return $this->PostReaction()
                 ->select('attr_id', DB::raw('count(*) as total,attr_id'))
                 ->groupBy('attr_id')
                 ->get();

Have you tried $this->PostReaction->count() ; without the () in PostReaction? It is a dynamic property provided automatically by Eloquent.

Make sure to define a relationship in the PostReaction Model too the PostReaction belongsTo one Post.

If the post has many reactions I think it should be clearer to call the method reactions and count the reactions like that : $post->reactions->count(); If you want to get only the 'likes' you can chain the conditions like that : $post->reactions->where('reaction', 'like')->count();

For more details you can check the OneToMany relashionship in the documentation

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