How do I get the count of a relationship with some constraints?

Posted 3 months ago by maidul98

I want to get the count of unread messages along with each convo. Here is what I have.

My relationship is as such: public function unseen(){ return $this->hasMany('App\Message', 'seen'); }

Everything in bellow works, just not the withCount part. I want to get total unread messages from everyone who is not the current user in this convo. In the messages table, i have seen to 0 by default and when seen it becomes 1.

Conversation::where(function ($query) { $query->where('fulfiller_id', '=', Auth::user()->id)->orWhere('wanter_id', '=', Auth::user()->id); })->with('want', 'fulfiller', 'wanter')->orderBy('updated_at', 'desc')->withCount( ['unseen' => function ($query) { $query->where('seen', 0, )->where('user_id' , '!=', Auth::user()->id)); }])->get();

When i do this, I just get zero for all of the convos, which is not true. What am i missing?

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

Reply to

Use Markdown with GitHub-flavored code blocks.