Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

binggle's avatar

how to query with relation's 'having count greater than' condition

I have 3 models. User / Post / Category

Following is my model code, models are simple.

// User class
class User extends Model
{
    public function posts(){
        return $this->hasMany( Post::class);
    }
}

// Post class
class Post extends Model
{
    $fillable = ['reg_date', ...];
    function user(){
        return $this->belongsTo( User::class);
    }
    function category(){
        return $this->belongsTo( Category::class);
    }
}

// Category class
class Category extends Model
{
    public function posts(){
        return $this->hasMany( Post::class);
    }
}

Post has 'reg_date' field

I want to get users list who wrote posts at 'reg_date' = '2022-10-01' more than 2 times, and the the category_id = 9.

How can I make this query ?

I guess the query should be something like this.

$users = User::query()
        ->whereHas(['posts', function($q){
            $q->where('post_cat_id', 9);
            $q->where('reg_date', '2022-10-01');
            ;;
        }])
        ->get();

Somebody can help me ?

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You can add a count as third and fourth parameter (also remove the [])

$users = User::query()
        ->whereHas('posts', function($q){
            $q->where('post_cat_id', 9);
            $q->where('reg_date', '2022-10-01');
            ;;
        }, '>', 3)
        ->get();
1 like

Please or to participate in this conversation.