Clear Laravel orderBy

I have a generic function that gives me general queries, for example:

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 throughout my project, but at a certain point I need to use this set of queries, but change ORDER BY, like this:

public static function get_specific_field(){
  return self::get_queryset()->select('singlefield')->orderBy('singlefield');
}

If I run this code, ORDER BY will simply add to the previous one and create an invalid query since "somefield" is not in the SELECTed fields. those.:

SELECT singlefield FROM table ORDER BY somefield ASC, singlefield ASC

How to clear orderBy so that I can just reuse the queries?

+4
source share
3 answers

, clearOrderBy(). orderbys Illuminate\Database\Query\Builder, . :

$query = YourModel::where('status', 1)->orderBy('created_at','desc');
// ... lots of other code, something needs to reset the order by ...
$query->getQuery()->orders = null;
$query->orderBy('other_column', 'desc');

, , (Illuminate\Database\Query\Query). , :

$query = YourModel::find(1)->load('children', function ($query) {
    $query->getBaseQuery()->orders = null;
});

. PR clearOrderBy().

+14

"" ?

class Model extends Eloquent {
  public static function get_queryset($orderBy = 'somefield'){
    $queryset = self::where('foo','=','bar');
    // Do tons of stuff with the query and then...
    return $queryset->orderBy($orderBy);
  }
}

public static function get_specific_field(){
  return self::get_queryset('singlefield')->select('singlefield');
}
+2
0

All Articles