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

davidavsira's avatar

hasManyThrough withCount gruopBy

Hi,

I have a DB with 3 tables: 'projects', 'buildings', 'apartments'.

in my Projects model I've added:

hasManyThrough('Apartment', 'Buildings');

every apartment have a "sold" column.

I'm trying to get an object looks something like this:

project: {
    ...
    buildings{
        0: {
            ...
            apartments_count: x,
            available_count: y
        },
        1: {
            ...
            apartments_count: x,
            available_count: y
        }
    }
}

I couldn't get it to work.

any ideas?

thanks.

0 likes
3 replies
Borisu's avatar

You can add a scope to get those values

public function scopeApartmentsCount($query)
{
    return $query->withCount('apartments');
}

and for the active

public function scopeAvailableCount($query)
{
    return $query->with(['apartments' => function($q) { return $q->where('active', true); }]);
}

This should do it.

davidavsira's avatar

Thanks, but thats not what I needed.

because I've got multiple Buildings, when I tried to do this:

public function scopeApartmentsCount($query)
{
    return $query->withCount('apartments');
}

Im getting the total count of apartments in all buildings. I wanted to count every apartments in every Building.

So, heres what I did: (and it's working, but if you thinks theres a better way - I'll be happy to see)

Projects::with(['buildings' => function($query){
            $query->withCount([
                'apartments',
                'apartments as sold' => function($query){
                    $query->where('sold', true);
                }]);
        }])->get();
Borisu's avatar

Ah right, I missed that. As long as it works, good job.

Please or to participate in this conversation.