I have a generic function which gives me generic querysets, something like:
class Model extends Eloquent {
public static function get_queryset(){
$queryset = self::where('foo','=','bar');
// Do tons of stuff with the query and then...
return $queryset->orderBy('somefield');
}
}
This function is used everywhere my project, but in a specific point I need to use this queryset but changing the ORDER BY, much like this:
public static function get_specific_field(){
return self::get_queryset()->select('singlefield')->orderBy('singlefield');
}
If I run this code, the ORDER BY will just append onto the previous and generate an invalid query, since the "somefield" is not on the SELECTed fields. i.e.:
SELECT singlefield FROM table ORDER BY somefield ASC, singlefield ASC
How do I clear the orderBy so I can just reuse querysets?
Here is a simple solution , tiny package you can use it by simply calling
->clearOrdersBy()
https://github.com/phpfalcon/laravel-clear-orders-byWhy not "genericise" your queryset?
Then you can use
I agree there should be a
clearOrderBy()
method added to the query builder. However because the registry of orderbys is a public property onIlluminate\Database\Query\Builder
you actually can clear it yourself today. The trick is getting access to the base query object:At other times, for example when manipulating a relation query, you need to get to access the base query (
Illuminate\Database\Query\Query
). So for example:Thats it. I plan to submit a PR for a
clearOrderBy()
as well.In Laravel 7, there's now a method to remove the orders from the query builder (#32186):