获取过去 48 小时内至少有 2 条评论的帖子

mic*_*cky 1 php laravel eloquent

我正在尝试获取过去 48 小时内至少有 2 条评论的所有帖子。我正在使用以下代码:

    $posts= Post::has( 'comments', '>', 1 )->whereHas( 'comments', function( $comments ) {
        return $comments->where( 'created_at', '>', Carbon::now()->subDays(2) );
    })->get()->toArray();
Run Code Online (Sandbox Code Playgroud)
  1. 至少有 2 条评论即可正常工作。
  2. 在过去 48 小时内无法正常工作。

小智 5

我认为问题是你正在使用has()withwhereHas()而不是这样做,你应该只使用 thewhereHas()来代替。

$posts = Post::whereHas('comments', function($query) {
    $query->where('created_at' ,'>', Carbon::now()->subDays(2))
}, '>', 1)->get();
Run Code Online (Sandbox Code Playgroud)

查询关系是否存在