From 6265f381c1c43df571407d825f3683eb22cab276 Mon Sep 17 00:00:00 2001 From: Luis Arce Date: Sat, 7 Oct 2023 21:51:43 -0500 Subject: [PATCH] Add Sorts docs --- README.md | 41 ++++++++++++++++++++++++++++++++++++ tests/Sorts/CaseSortTest.php | 4 ++++ 2 files changed, 45 insertions(+) diff --git a/README.md b/README.md index 7153a7f..856cdf1 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,47 @@ QueryBuilder::for(Book::class) ]); ``` +### Sorts + +#### RelationSort + +To sort by fields of related tables you must use `join`, there is no easy way to do it from eloquent, +so you can use `TeamQ\QueryBuilder\Sorts\RelationSort`, this class receives the type of `join` as a parameter. + +```php +use Spatie\QueryBuilder\AllowedFilter; +use Spatie\QueryBuilder\QueryBuilder; +use TeamQ\QueryBuilder\Sorts\RelationSort; + +QueryBuilder::for(Book::class) + ->allowedSorts([ + AllowedSort::custom('author.name', new RelationSort(JoinType::Inner)), + ]) +``` + +#### CaseSort + +If you use enums or states, where each enum or state is represented by a number, you may want to sort by name +of that enum or state and not by the number, then you can use `TeamQ\QueryBuilder\Sorts\CaseSort`. + +You must pass an array `[$key => $value]`, which will be used to generate the sort. + +```php +use Spatie\QueryBuilder\AllowedFilter; +use Spatie\QueryBuilder\QueryBuilder; +use TeamQ\QueryBuilder\Sorts\CaseSort; + +QueryBuilder::for(Book::class) + ->allowedSorts([ + AllowedSort::custom('state', new CaseSort([ + 1 => 'Active', + 2 => 'Rejected', + 3 => 'Deleted', + 4 => 'Completed', + ])), + ]); +``` + ## Testing Can use docker-compose to run diff --git a/tests/Sorts/CaseSortTest.php b/tests/Sorts/CaseSortTest.php index 2b75660..cedf2e6 100644 --- a/tests/Sorts/CaseSortTest.php +++ b/tests/Sorts/CaseSortTest.php @@ -69,3 +69,7 @@ fn ($book) => $book->classification->toBe(BookClassificationEnum::Adults), ); }); + +it('sort records by relationship fields', function () { + +})->skip('WIP');