清除Laravel的命令

Raf*_*rra 8 php laravel eloquent

我有一个泛型函数,它给我通用查询集,如:

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

这个函数在我的项目的任何地方都使用,但在特定的一点我需要使用这个查询集但是更改 ORDER BY,就像这样:

public static function get_specific_field(){
  return self::get_queryset()->select('singlefield')->orderBy('singlefield');
}
Run Code Online (Sandbox Code Playgroud)

如果我运行此代码,ORDER BY将仅附加到前一个并生成无效查询,因为"somefield"不在SELECTed字段上.即:

SELECT singlefield FROM table ORDER BY somefield ASC, singlefield ASC
Run Code Online (Sandbox Code Playgroud)

如何清除orderBy以便我可以重用查询集?

jps*_*der 24

我同意应该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');
Run Code Online (Sandbox Code Playgroud)

在其他时候,例如在操作关系查询时,您需要访问基本查询(Illuminate\Database\Query\Query).例如:

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

而已.我打算同时提交PR clearOrderBy().


Nik*_*lay 7

reorder()由于这是一个相当老的问题,并且可能大多数人已经升级到 Laravel 7 及更高版本,因此您可以使用 @halloei 提到的内置方法( #32186)。

但是,如果您坚持使用 Laravel 7 版,您可以使用 PR 中的想法制作一个宏。然后你就可以像使用 Laravel 7 一样使用。reorder()只需在AppServiceProvider@boot.

\Illuminate\Database\Query\Builder::macro('reorder', function ($column = null, $direction = 'asc') {
   $this->orders = null;
   $this->unionOrders = null;
   $this->bindings['order'] = [];
   $this->bindings['unionOrder'] = [];

   if ($column) {
      return $this->orderBy($column, $direction);
   }

   return $this;
});
Run Code Online (Sandbox Code Playgroud)


hal*_*oei 5

在 Laravel 7 中,现在有一种方法可以从查询构建器中删除订单(#32186):

public static function get_specific_field(){
    return self::get_queryset()->select('singlefield')->reorder('singlefield');
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ker 2

为什么不“泛化”你的查询集?

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

public static function get_specific_field(){
  return self::get_queryset('singlefield')->select('singlefield');
}
Run Code Online (Sandbox Code Playgroud)

  • 并不是我不能这样做,但仍然应该有一种方法来清除所订购的内容 (2认同)