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

deansatch's avatar

count 3rd level relationship items

I want to get a total number of classes & total number of class bookings per studio (between certain dates). This query works to output [studio(with no. of classes)]->[classes]->[bookings]

So if I dd() I can expand bookings and see the array which i want to count.

$studios = \App\Studio::
        withCount([
            'classes'=> 
               function($q)use($start, $end){
                       $q->whereHas('classdates',function($q)use( $start, $end){
                               $q->whereBetween('datetime',[ $start, $end]);
                               });
             }])
                           
            ->with(['classes.classdates' =>
                function($q)use($start, $end){
                        $q->whereHas('classes.classdates',function($q)use( $start, $end){
                                $q->whereBetween('datetime',[ $start, $end]);
                            })
                            ->whereHas('classes.bookings');

                        }
                ,'classes.bookings'
                ])
                ->get();

I thought adding this (2nd bottom line) would work but it gives an error: Call to undefined method Illuminate\Database\Query\Builder::classes.bookings()

$studios = \App\Studio::
        withCount([
            'classes'=> 
               function($q)use($start, $end){
                       $q->whereHas('classdates',function($q)use( $start, $end){
                               $q->whereBetween('datetime',[ $start, $end]);
                               });
             }])
                           
            ->with(['classes.classdates' =>
                function($q)use($start, $end){
                        $q->whereHas('classes.classdates',function($q)use( $start, $end){
                                $q->whereBetween('datetime',[ $start, $end]);
                            })
                            ->whereHas('classes.bookings');

                        }
                ,'classes.bookings'
                ])
->withCount('classes.bookings')
                ->get();

I've tried a few ways of adding withCount() but it only seems to work on my first part...counting the classes

0 likes
2 replies
deansatch's avatar

Do i need to add any more information to get some help on this?

Please or to participate in this conversation.