Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort by translation using translatable along spatie/laravel-query-builder #27

Closed
bpuig opened this issue Jul 21, 2019 · 5 comments
Closed
Assignees
Labels

Comments

@bpuig
Copy link

bpuig commented Jul 21, 2019

Has anyone tried using translatable with spatie/laravel-query-builder ?
If so, how can I sort by translation fields?

Thanks

@bpuig bpuig added the question label Jul 21, 2019
@Gummibeer
Copy link
Member

I can't find anything in the docs about sorting by a join or scope.
So I would say you will have to tinker with it. But I will also check if I find a way.

@Gummibeer
Copy link
Member

@bpuig you will have to create a custom sort class: spatie/laravel-query-builder#91

@Gummibeer Gummibeer self-assigned this Jul 21, 2019
@Gummibeer
Copy link
Member

#25 could help you to write the sort class and handle translatable and normal attributes in it.

@bpuig
Copy link
Author

bpuig commented Jul 22, 2019

Perfect! I'm glad that it seems possible, I'll give it a try and then write my results in case it's useful to someone

@bpuig
Copy link
Author

bpuig commented Jul 24, 2019

Got it!
First on spatie's query builder add one or many custom sort:

use Spatie\QueryBuilder\Sort;

...

->allowedSorts(Sort::custom('name', new BookSort(), 'name', Sort::custom('description', new BookSort(), 'description')

Then create a class:

use Illuminate\Database\Eloquent\Builder;
use Spatie\QueryBuilder\Sorts\Sort;

class BookSort implements Sort
{
    public function __invoke(Builder $query, $descending, string $property) : Builder
    {
        return $query->OrderByTranslation($property, $descending ? 'desc' : 'asc');
    }
}

And voilà! It works.

@bpuig bpuig closed this as completed Jul 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants