diff --git a/src/Sieve.php b/src/Sieve.php index 56bf33a..36ac48e 100644 --- a/src/Sieve.php +++ b/src/Sieve.php @@ -12,6 +12,8 @@ class Sieve protected $defaultSort = null; + protected $sortable = []; + public function __construct(Request $request) { $this->request = $request; @@ -37,7 +39,7 @@ public function getFilters() public function apply($queryBuilder) { foreach ($this->getFilters() as $sieveFilter) { - /** @var Filter */ + /** @var ModifiesQueries */ $filter = $sieveFilter['filter']; $property = $sieveFilter['property']; @@ -77,6 +79,16 @@ public function apply($queryBuilder) if ($this->getSort() == "$property:asc") { $queryBuilder->orderBy($column, "asc"); } + + if ($this->getSort() == "$property:asc_nulls_last") { + $queryBuilder->orderByRaw("ISNULL(\"$column\") asc") + ->orderBy($column, 'asc'); + } + + if ($this->getSort() == "$property:desc_nulls_first") { + $queryBuilder->orderByRaw("ISNULL(\"$column\") desc") + ->orderBy($column, 'desc'); + } } return $this; diff --git a/tests/SieveTest.php b/tests/SieveTest.php index a7dfad1..6026b06 100644 --- a/tests/SieveTest.php +++ b/tests/SieveTest.php @@ -74,6 +74,54 @@ public function applies_sieve_sorts_to_a_query_builder_asc() ); } + /** + * @test + */ + public function applies_sieve_sorts_to_a_query_builder_asc_nulls_last() + { + $request = Request::create('/', 'GET', [ + 'sort' => 'name:asc_nulls_last', + ]); + + $seive = new Sieve($request); + $seive->addFilter('name', new StringFilter); + + /** @var Builder */ + $builder = $this->app->make(Builder::class); + $builder->from('pets'); + + $seive->apply($builder); + + $this->assertEquals( + 'select * from "pets" order by ISNULL("name") asc, "name" asc', + $builder->toSql() + ); + } + + /** + * @test + */ + public function applies_sieve_sorts_to_a_query_builder_desc_nulls_first() + { + $request = Request::create('/', 'GET', [ + 'sort' => 'name:desc_nulls_first', + ]); + + $seive = new Sieve($request); + $seive->addFilter('name', new StringFilter); + + /** @var Builder */ + $builder = $this->app->make(Builder::class); + $builder->from('pets'); + + $seive->apply($builder); + + $this->assertEquals( + 'select * from "pets" order by ISNULL("name") desc, "name" desc', + $builder->toSql() + ); + } + /** * @test */