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

bonzoSPb's avatar

withCount() and unionAll in Model

Example: we have 3 tables - users, posts, comments

In User.php

public function posts()
{
        return $this->hasMany('App\Post', 'user_id');
}

public function comments()
{
        return $this->hasMany('App\Comment', 'user_id');
}

And union of these two relationships

public function allActivities()
{
        return $this-> posts()->unionAll($this-> comments());
}

So, i call

User::withCount(['allActivities' => function($query) {
			$query->where('status' => 'show');
}])

This return me only count of posts, without comments.

But if i call

User::with(['allActivities' => function($query) {
			$query->where('status' => 'show');
}])

This return posts with comments.

Whats wrong with withCount?

0 likes
2 replies
Sinnbeck's avatar

Check the generated sql query using debugbar. I don't think it is build to work like this, so you will probably need some custom sql

Please or to participate in this conversation.