null
null

Reputation: 469

Sort a model by it's first related model in Laravel?

I have a model, Reservation, which hasMany serviceDates.

Is it possible in Laravel (5.3) to sort my Reservations by their first service dates 'date' column?

I've tried this...

$reservations = Reservation::with(['serviceDates' => function ($q) {
                            $q->orderBy('date', 'asc');
                        }])->get();

...but this doesn't seem to work because a Reservation hasMany serviceDates and doesn't have have 1 serviceDate.

Upvotes: 0

Views: 72

Answers (1)

nxu
nxu

Reputation: 2272

The reason it doesn't work is that eager loading in Laravel does not join the related tables, it selects them in a separate query instead.

The easiest solution in my opinion is to add the latest serviceDate as a subselect to your query and order it by that:

$reservations = Reservation::select('reservations.*')
    ->selectRaw('
        (SELECT MIN(date) FROM service_dates WHERE reservation_id = reservations.id) as service_date
    ')
    ->orderBy('service_date')
    ->get()

You can still eager load service dates if necessary.

Upvotes: 1

Related Questions