Skip to content

Commit

Permalink
Feat: add reorder method to clear and set sorting (#7016)
Browse files Browse the repository at this point in the history
  • Loading branch information
People-Sea authored Aug 23, 2024
1 parent f81983c commit 5e1bd42
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 5e1bd42

Please sign in to comment.