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

deansatch's avatar

group overal results by a relationship value

I have a table 'dates' which I want to return with('bookings'). The bookings table has a customer_id and that customer may be booked into several dates.

   public function bookings()
        {
            return $this->belongsTo('App\Booking');
        }

I am trying to count the number of customers that have booked between a date range. So, I want Date::with('bookings') then group the result set by bookings.customer_id.

I presume I can't do this with groupBy since it returns an array of all the dates with a single customer/booking per relationship.

i.e.

date1->bookings->[customer_id:5]

date2->bookings->[customer_id:5]

date2->bookings->[customer_id:3]

My brain is in a knot so if anyone can help that would be great!

0 likes
4 replies
deansatch's avatar

I did do a thorough read of the forums before posting. I don't think groupBy will be a possibility without redoing the relationships (which just isn't feasable)

jlrdw's avatar

Generally group by isn't well suited with orm.

jimmck's avatar

Group By works perfectly fine for dates. Eloquent is turned into 1 or more SQL statements. If Eloquent is lacking in a capability use the RAW option.

Please or to participate in this conversation.