Clear Laravel's orderBy

2020-08-10 09:18发布

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?

4条回答
小情绪 Triste *
2楼-- · 2020-08-10 09:53

Here is a simple solution , tiny package you can use it by simply calling ->clearOrdersBy() https://github.com/phpfalcon/laravel-clear-orders-by

查看更多
我只想做你的唯一
3楼-- · 2020-08-10 09:56

Why not "genericise" your queryset?

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);
  }
}

Then you can use

public static function get_specific_field(){
  return self::get_queryset('singlefield')->select('singlefield');
}
查看更多
Evening l夕情丶
4楼-- · 2020-08-10 09:57

I agree there should be a clearOrderBy() method added to the query builder. However because the registry of orderbys is a public property on Illuminate\Database\Query\Builder you actually can clear it yourself today. The trick is getting access to the base query object:

$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');

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:

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

Thats it. I plan to submit a PR for a clearOrderBy() as well.

查看更多
太酷不给撩
5楼-- · 2020-08-10 10:02

In Laravel 7, there's now a method to remove the orders from the query builder (#32186):

public static function get_specific_field(){
    return self::get_queryset()->select('singlefield')->reorder('singlefield');
}
查看更多
登录 后发表回答