Created
November 28, 2024 08:08
-
-
Save motion-work/fca48a6a8278c0890e8e0aa54cd996bc to your computer and use it in GitHub Desktop.
Statamic Custom Query - filteredPosts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\GraphQL\Queries; | |
| use GraphQL\Type\Definition\Type; | |
| use Illuminate\Support\Str; | |
| use Statamic\Facades\Entry; | |
| use Statamic\Facades\GraphQL; | |
| use Statamic\GraphQL\Middleware\ResolvePage; | |
| use Statamic\GraphQL\Queries\Concerns\FiltersQuery; | |
| use Statamic\GraphQL\Queries\Query; | |
| use Statamic\GraphQL\Types\JsonArgument; | |
| class FilteredPostsQuery extends Query | |
| { | |
| use FiltersQuery; | |
| protected $attributes = [ | |
| 'name' => 'filteredPosts', | |
| ]; | |
| protected $middleware = [ | |
| ResolvePage::class, | |
| ]; | |
| public function type(): Type | |
| { | |
| return GraphQL::paginate( | |
| GraphQL::type('Entry_Blog_Post') | |
| ); | |
| } | |
| public function args(): array | |
| { | |
| return [ | |
| 'limit' => GraphQL::int(), | |
| 'page' => GraphQL::int(), | |
| 'site' => GraphQL::string(), | |
| 'filter' => GraphQL::type(JsonArgument::NAME), | |
| 'sort' => GraphQL::listOf(GraphQL::string()), | |
| ]; | |
| } | |
| public function resolve($root, $args) | |
| { | |
| $filters = $args['filter'] ?? []; | |
| $query = Entry::query() | |
| ->where('site', $args['site']) | |
| ->where('collection', 'blog') | |
| ->whereIn('blueprint', ['post', 'cluster']); | |
| foreach ($filters as $key => &$definitions) { | |
| if (isset($definitions['json_contains']) && is_array($definitions['json_contains'])) { | |
| $query->whereJsonContains($key, $definitions['json_contains']); | |
| unset($definitions['json_contains']); | |
| } | |
| } | |
| $this->filterQuery($query, $filters); | |
| $this->sortQuery($query, $args['sort'] ?? []); | |
| return $query->paginate($args['limit'] ?? 1000); | |
| } | |
| private function sortQuery($query, $sorts) | |
| { | |
| if (empty($sorts)) { | |
| $sorts = ['date']; | |
| } | |
| foreach ($sorts as $sort) { | |
| $order = 'desc'; | |
| if (Str::contains($sort, ' ')) { | |
| [$sort, $order] = explode(' ', $sort); | |
| } | |
| $query->orderBy($sort, $order); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment