TechnicalEloquent performance

Eloquent performanceLesson 18 of 28

Options for Ordering by a BelongsToMany Relationship

belongsToMany: treat the pivot as a hasMany and use subqueries.

1 min readIntermediateLesson

Eloquent performance18

The problem

A library: users borrow books through a checkouts pivot table. Sort books by when they were last borrowed, or by who borrowed them last.

The fix

Sorting by a pivot column is really a hasMany, so use a subquery. Sorting by a column on the far side needs a subquery with a join inside.

✕ Instead of this

Book::join('checkouts', 'checkouts.book_id', '=', 'books.id')
    ->select('books.*')
    ->orderByDesc('checkouts.borrowed_date');
// a row per checkout: each book repeats

✓ Do this

Book::orderByDesc(fn ($q) => $q->select('borrowed_date')
    ->from('checkouts')
    ->whereColumn('book_id', 'books.id')
    ->latest('borrowed_date')
    ->limit(1)
);

The benefit

Each book appears once, sorted by its latest checkout.

More detail

By the name of the last borrower (far side):

->orderBy(User::select('name')
    ->join('checkouts', 'checkouts.user_id', '=', 'users.id')
    ->whereColumn('checkouts.book_id', 'books.id')
    ->latest('checkouts.borrowed_date')
    ->take(1))

Watch out

  • With lots of data the far-side version won't be fast. Consider storing last_checkout_id on books and updating it on each checkout.

Frame from lesson 18

Ordering books by the name of their last borrower: orderBy(User::select('name')->join('checkouts', ...)->whereColumn('checkouts.book_id', 'books.id')). The latest() / take(1) are added next.

Key takeaway

belongsToMany: treat the pivot as a hasMany and use subqueries.

Check yourself

Sorting books by last borrowed date: which earlier lesson's technique does this reuse?

Reveal answer

✓ Answer

Lesson 17 (hasMany). A book has many checkouts.