I’m trying to get all posts that has at least 2 comments in the last 48 hours. I’m using the following code:
$posts= Post::has( 'comments', '>', 1 )->whereHas( 'comments', function( $comments ) {
return $comments->where( 'created_at', '>', Carbon::now()->subDays(2) );
})->get()->toArray();
- has at least 2 comments is working fine.
- in the last 48 hours isn’t working.
4
Answers
I think the problem is that you are using
has()
withwhereHas()
instead of doing that you should only use thewhereHas()
instead.Querying Relationship Existence
Your query is
'created_at', '>', Carbon::now()->subDays(2)
It means
created_at
has been more than 48 hours from todayBut it should be less then 48 hours from today
So, try this
'created_at', '<', Carbon::now()->subDays(2)
maybe this will help