Closed webard closed 2 years ago
In v1 operators converted into directives (#18) and use Argument
instead of array. Technically, you can try apply filters something like:
but, if I remember correctly, it will not throw an error if SearchByConditionTest
is not a valid type name that makes writing code harder.
Your way, there is an Exception:
Conditions for `LastDragon_ru\LaraASP\GraphQL\SearchBy\Directives\Directive` are invalid.
My code:
<?php
declare(strict_types=1);
namespace Core\Abilities;
use Illuminate\Contracts\Container\Container;
use Illuminate\Database\Eloquent\{Builder as EloquentBuilder, Model};
use Illuminate\Database\Query\Builder as QueryBuilder;
use GraphQL\Language\Parser;
use LastDragon_ru\LaraASP\GraphQL\SearchBy\Directives\Directive;
trait Filterable
{
private Container $operatorsContainer;
/**
* @param EloquentBuilder<Model>|QueryBuilder $query
* @param array<mixed> $filters
*
* @return EloquentBuilder<Model>|QueryBuilder
*/
public function scopeFilter(EloquentBuilder|QueryBuilder $builderFactory, array $filters): EloquentBuilder|QueryBuilder
{
$definitionNode = Parser::inputValueDefinition('input: SearchByConditionTest');
$directiveNode = Parser::directive('@test');
$directive = app()->make(Directive::class)->hydrate($directiveNode, $definitionNode);
$builder = $builderFactory;
$actual = $directive->handleBuilder($builder, $filters);
return $actual;
}
}
and usage:
$data = User::filter(
[
'anyOf' => [
[
'email' => [
'equal' => "%gmail%"
]
],
[
'email' => [
'equal' => "%live%"
]
]
]
],
)->first();
Looks like $filters must be ArgumentSet, but is array.
Instead of SearchByConditionTest
you should use the actual type same as in users
query. If type invalid (or $filters
array has a wrong structure) generated Argument
will have invalid structure => query will fail.
You can try to play/debug the following code to check that type name/$filter
valid (directive doing the same):
$definitionNode = Parser::inputValueDefinition('input: SearchByConditionTest');
$argument = $this->getFactory()->getArgument($definitionNode, $filter);
Ok, seems to work, but now it is necessary to have filter input for every Model.
Thank you for help.
You are welcome)
In version before 1.0.0 I had trait:
which allows me to run filters on models like this:
On version 1.0.0, filter mechanism was rewritten, and code stops work. Is there a possibility to run filters programmaticaly? I know it is "side functionality", but it is very helpful to store filters in database as JSON.