pickab00
3 months ago
143
3
Laravel

Counting 'as' in Laravel

Posted 3 months ago by pickab00

I want to count my pivot relationship but I have a where condition which I need to run and I am not sure how to do that. Here is the code.

$comments = Article::with(['comments.replies' => function($q){
        $q->where('approved', 1)->get(); //this bit works as intended. not the issue
    }])->with(['comments.commentlikes' => function($q){
        $q->where('like', 1)->where('commentlikes_type', 'App\Comment')->count(); //here is the issue
    }])->findOrFail($id);

The issue is where it says, comments.commentlikes. Can I do a withCount and do a where condition? The thing is that I am foreach looping (not on laravel but this is an API call to another application). So basically I want to display the comments and its replies which is working fine. But I want to display the count of likes and dislikes for each comment/reply as well. My commentlikes page is like this:

id
commentlikeable_id
commentlikeable_type
like
dislike
ip

So I have a like and dislike on the table. If a user likes a comment, the commentable_type becomes App\Comment and if it is a reply it becomes App\Reply with like 1 or dislike 1 depending on if it is a like or dislike. So what I want to do is, have a count foreach of my likes and dislikes when I iterate through the data. Something like this

//This is the first comment and its likes with its replies and replies likes and dislikes

comment1: likes count 2
comment1: dislikes count 5

  reply1: likes count 2
  reply1: dislikes count 0

  reply2: likes count 0
  reply2: dislikes count 2


//This is the second comment and its likes with its replies and replies likes and dislikes

comment2: likes count 1
comment2: dislikes count 0

  reply1: likes count 4
  reply1: dislikes count 3

  reply2: likes count 2
  reply2: dislikes count 5

I didn't know how else to explain that. Basically that's what I want to iterate and how I want it to look like

Please sign in or create an account to participate in this conversation.