diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index 4df54acdd578..144cb5e84023 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -2017,6 +2017,25 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') ->limit($perPage); } + /** + * Remove all existing orders and optionally add a new order. + * + * @return $this + */ + public function reorder($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; + } + /** * Get an array with all orders with a given column removed. * diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index 070cb9b8eaec..33c62b2787a3 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -1108,6 +1108,35 @@ public function testOrderBys() $this->assertEquals([1, 1, 'news', 'opinion'], $builder->getBindings()); } + 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 testOrderBySubQueries() { $expected = 'select * from "users" order by (select "created_at" from "logins" where "user_id" = "users"."id" limit 1)';