Skip to content

Commit

Permalink
[5.x] Add reorder() query builder method (#10871)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanmitchell authored Oct 1, 2024
1 parent 2d3bdc6 commit 6faf9f5
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,17 @@ public function orderByDesc($column)
return $this->orderBy($column, 'desc');
}

public function reorder($column = null, $direction = 'asc')
{
$this->orderBys = [];

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

return $this;
}

abstract public function inRandomOrder();

public function where($column, $operator = null, $value = null, $boolean = 'and')
Expand Down
13 changes: 13 additions & 0 deletions src/Query/EloquentQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,19 @@ public function orderBy($column, $direction = 'asc')
return $this;
}

public function reorder($column = null, $direction = 'asc')
{
if ($column) {
$this->builder->reorder($this->column($column), $direction);

return $this;
}

$this->builder->reorder();

return $this;
}

protected function column($column)
{
return $column;
Expand Down
10 changes: 10 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,16 @@ public function entries_are_found_using_lazy()
$this->assertCount(3, $entries);
}

#[Test]
public function entries_can_be_reordered()
{
$this->createDummyCollectionAndEntries();

$this->assertSame(['post-3', 'post-2', 'post-1'], Entry::query()->orderBy('title', 'desc')->get()->map->slug()->all());

$this->assertSame(['post-1', 'post-2', 'post-3'], Entry::query()->orderBy('title', 'desc')->reorder()->orderBy('asc', 'desc')->get()->map->slug()->all());
}

#[Test]
public function filtering_using_where_status_column_writes_deprecation_log()
{
Expand Down

0 comments on commit 6faf9f5

Please sign in to comment.