Skip to content

Commit

Permalink
[7.x] Add the ability to remove orders from the query builder (larave…
Browse files Browse the repository at this point in the history
…l#32186)

* Add the ability to remove orders from the query builder

* Update Builder.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
2 people authored and imacrayon committed Mar 31, 2020
1 parent 6161ccd commit f2272f7
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)';
Expand Down

0 comments on commit f2272f7

Please sign in to comment.