[7.x] Add the ability to remove orders from the query builder #32186
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
[Replaces #32176]
It's really nice to be able to define default orders on models and relationships. For example:
Now when you access
$account->users
, the users will be sorted properly. And the same goes for if you use the$account->users()
query builder. Nice. 👍However, this can be problematic if you ever need to order the relationship by something else. For example:
Because of the default
orderBy()
on the relationship, this will still first sort by thename
, and then by theemail
, which may not be desirable.This happens because new orders get added to the query builder, they do not replace existing orders. And that's good behaviour. But then how do you handle those situations where you really do want to remove the default order by? Right now you'd have to stop using the relationship, and just use the model directly, which isn't ideal.
This PR adds a very simple
reorder($column = null, $direction = null)
method to the query builder that lets you quickly remove all the existing orders, and optionally add a new one. Here's how you would use it:This syntax is inspired by the Rails reorder method, which does the same thing.