diff --git a/src/Query/Builder.php b/src/Query/Builder.php index d92e6ee..16f301d 100755 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -2117,6 +2117,25 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') return $this->orderBy($column, 'asc')->limit($perPage); } + /** + * Remove all existing orders and optionally add a new order. + * + * @param Closure|Expression|ModelBuilder|static|string $column + */ + public function reorder(mixed $column = null, string $direction = 'asc'): static + { + $this->orders = null; + $this->unionOrders = null; + $this->bindings['order'] = []; + $this->bindings['unionOrder'] = []; + + if ($column) { + return $this->orderBy($column, $direction); + } + + return $this; + } + /** * Add a union statement to the query. * diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 0a1d416..95f0a51 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -857,6 +857,35 @@ public function testOrderBys() $this->assertEquals('select * from "users" order by "name" desc', $builder->toSql()); } + public function testReorder() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->orderBy('name'); + $this->assertSame('select * from "users" order by "name" asc', $builder->toSql()); + $builder->reorder(); + $this->assertSame('select * from "users"', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->orderBy('name'); + $this->assertSame('select * from "users" order by "name" asc', $builder->toSql()); + $builder->reorder('email', 'desc'); + $this->assertSame('select * from "users" order by "email" desc', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('first'); + $builder->union($this->getBuilder()->select('*')->from('second')); + $builder->orderBy('name'); + $this->assertSame('select * from "first" union select * from "second" order by "name" asc', $builder->toSql()); + $builder->reorder(); + $this->assertSame('select * from "first" union select * from "second"', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->orderByRaw('?', [true]); + $this->assertEquals([true], $builder->getBindings()); + $builder->reorder(); + $this->assertEquals([], $builder->getBindings()); + } + public function testHavings() { $builder = $this->getBuilder();