Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6.0] Add the ability to order by subqueries #29563

Merged
merged 1 commit into from Aug 14, 2019

Conversation

@reinink
Copy link
Contributor

commented Aug 14, 2019

This PR adds the ability to order by subqueries using the existing orderBy($column, $direction = 'asc') and orderByDesc($column) methods.

Previously this was only possible using orderByRaw(), but that's dangerous, as the direction (asc/desc) cannot be set with a binding, meaning developers were responsible for verifying and inserting the direction into the query themselves.

Here are a couple examples of how this can be useful.

// Order users by their last login date
$users = User::orderBy(function ($query) {
    $query->select('created_at')
        ->from('logins')
        ->whereColumn('user_id', 'users.id')
        ->latest()
        ->limit(1);
})->get();

// Order courses by the start date of the first lesson
$courses = Course::orderBy(
    Lesson::select('starts_at')
        ->whereColumn('course_id', 'courses.id')
        ->oldest('starts_at')
        ->limit(1)
)->get();

Note, orderBy() now accepts subqueries in three possible formats:

  • Illuminate\Database\Query\Builder
  • Illuminate\Database\Eloquent\Builder
  • Closure

This is the exact same approach as what's done in the whereIn() method:

if ($values instanceof self ||
$values instanceof EloquentBuilder ||
$values instanceof Closure) {
[$query, $bindings] = $this->createSub($values);
$values = [new Expression($query)];
$this->addBinding($bindings, 'where');
}

@reinink reinink force-pushed the reinink:order-by-sub-queries branch from e79b13a to 8c994c3 Aug 14, 2019

@taylorotwell taylorotwell merged commit acbbfea into laravel:master Aug 14, 2019

2 checks passed

continuous-integration/styleci/pr The analysis has passed
Details
continuous-integration/travis-ci/pr The Travis CI build passed
Details

@reinink reinink deleted the reinink:order-by-sub-queries branch Aug 14, 2019

@GrahamCampbell GrahamCampbell changed the title Add the ability to order by subqueries [6.0] Add the ability to order by subqueries Aug 14, 2019

@ninjaparade

This comment has been minimized.

Copy link
Contributor

commented Aug 14, 2019

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.