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

Support relationship aliases #8

Merged
merged 9 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/Filters/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ abstract class Filter implements IFilter
{
use HasPropertyRelationship;

protected ?JoinType $joinType = null;

protected const ARRAY_OPERATORS = [];

/**
Expand All @@ -39,10 +37,12 @@ abstract protected function handle(
/**
* Filter constructor.
*/
public function __construct(bool $addRelationConstraint = true, JoinType $joinType = null)
{
public function __construct(
bool $addRelationConstraint = true,
private readonly ?JoinType $joinType = null,
private readonly array|string|null $joinAliases = null,
) {
$this->addRelationConstraint = $addRelationConstraint;
$this->joinType = $joinType;
}

/**
Expand Down Expand Up @@ -116,9 +116,13 @@ protected function withJoinConstraint(Builder $query, $value, string $property):
$relation = $relation->getRelation($partial);
}

$query->joinRelationship($relationName, joinType: $this->joinType->value);
$query->joinRelationship($relationName, $this->joinAliases, $this->joinType->value);

$this->relationConstraints[] = $property = $relation->qualifyColumn($property);
if (is_string($this->joinAliases)) {
$this->relationConstraints[] = $property = $this->joinAliases.'.'.$property;
} else {
$this->relationConstraints[] = $property = $relation->qualifyColumn($property);
}

$this->__invoke($query, $value, $property);
}
Expand Down
21 changes: 16 additions & 5 deletions src/Filters/GlobalFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,23 @@ class GlobalFilter implements Filter

protected readonly array $fields;

protected readonly array|string|null $joinAliases;

protected ?JoinType $joinType = null;

/**
* @param array<string|Expression> $fields
*/
public function __construct(array $fields, bool $addRelationConstraint = true, JoinType $joinType = null)
{
public function __construct(
array $fields,
bool $addRelationConstraint = true,
?JoinType $joinType = null,
array|string|null $joinAliases = null
) {
$this->fields = $fields;
$this->addRelationConstraint = $addRelationConstraint;
$this->joinType = $joinType;
$this->joinAliases = $joinAliases;
}

/**
Expand All @@ -41,7 +48,7 @@ public function __construct(array $fields, bool $addRelationConstraint = true, J
public static function allowed(
array $fields,
bool $addRelationConstraint = true,
JoinType $joinType = null,
?JoinType $joinType = null,
string $name = 'global',
): AllowedFilter {
return AllowedFilter::custom($name, new static($fields, $addRelationConstraint, $joinType));
Expand Down Expand Up @@ -123,9 +130,13 @@ protected function setJoinsRelationship(Builder $query, string $property): void
$relation = $relation->getRelation($partial);
}

$query->joinRelationship($relationName, joinType: $this->joinType->value);
$query->joinRelationship($relationName, $this->joinAliases, $this->joinType->value);

$this->relationConstraints[] = $relation->qualifyColumn($property);
if (is_string($this->joinAliases)) {
$this->relationConstraints[] = $this->joinAliases.'.'.$property;
} else {
$this->relationConstraints[] = $relation->qualifyColumn($property);
}
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/Sorts/RelationSort.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class RelationSort implements Sort
public function __construct(
private readonly JoinType $joinType = JoinType::Inner,
private readonly ?AggregationType $aggregationType = null,
private readonly array|string|null $joinAliases = null,
) {
}

Expand All @@ -39,7 +40,8 @@ public function __invoke(Builder $query, bool $descending, string $property): vo
$property,
$descending ? 'desc' : 'asc',
$this->aggregationType?->value,
$this->joinType->value
$this->joinType->value,
$this->joinAliases,
);
}
}
63 changes: 63 additions & 0 deletions tests/Filters/PowerJoins/TextFilterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use TeamQ\QueryBuilder\Enums\Comparators;
use TeamQ\QueryBuilder\Enums\JoinType;
use TeamQ\QueryBuilder\Filters\TextFilter;
use Tests\Mocks\Models\Country;
use Tests\Mocks\Models\Flight;

beforeEach(function () {
$this->request = new Illuminate\Http\Request();
$this->request->setMethod(Request::METHOD_GET);

$belgium = Country::factory()->create(['name' => 'Belgium', 'code' => 'BE']);
$ecuador = Country::factory()->create(['name' => 'Ecuador', 'code' => 'EC']);

$this->firstFlight = Flight::factory()
->for($belgium, 'departure')
->for($ecuador, 'arrival')
->create([
'code' => '7485',
]);

$this->secondFlight = Flight::factory()
->for($ecuador, 'departure')
->for($belgium, 'arrival')
->create([
'code' => '8596',
]);
});

it('apply relationships using aliases that point to the same table', function () {
$this->request->query->add([
'filter' => [
'departure.name' => [
'value' => 'gium',
'operator' => Comparators\Text::EndWith->value,
],
'arrival.name' => [
'value' => 'cuado',
'operator' => Comparators\Text::Contains->value,
],
],
]);

$queryBuilder = QueryBuilder::for(Flight::class, $this->request)
->allowedFilters([
AllowedFilter::custom('departure.name', new TextFilter(false, JoinType::Inner, 'departure')),
AllowedFilter::custom('arrival.name', new TextFilter(false, JoinType::Inner, 'arrival')),
]);

expect($queryBuilder->toSql())
->toBe(
'select `flights`.* from `flights` inner join `countries` as `departure` on `flights`.`departure_id` = `departure`.`id` inner join `countries` as `arrival` on `flights`.`arrival_id` = `arrival`.`id` where lower(`departure`.`name`) like ? and lower(`arrival`.`name`) like ?'
)
->and($queryBuilder->get())
->toHaveCount(1)
->sequence(
fn ($flight) => $flight->code->toBe('7485')
);
});
26 changes: 26 additions & 0 deletions tests/Mocks/Database/Factories/FlightFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Tests\Mocks\Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Tests\Mocks\Models\Country;
use Tests\Mocks\Models\Flight;

class FlightFactory extends Factory
{
protected $model = Flight::class;

/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'departure_id' => Country::factory(),
'arrival_id' => Country::factory(),
'code' => fake()->colorName(),
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up(): void
{
Schema::create('flights', function (Blueprint $table) {
$table->id();
$table->foreignId('departure_id')->constrained('countries');
$table->foreignId('arrival_id')->constrained('countries');
$table->string('code');
$table->timestamps();
});
}

public function down(): void
{
Schema::dropIfExists('flights');
}
};
6 changes: 6 additions & 0 deletions tests/Mocks/Models/Author.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Tests\Mocks\Database\Factories\AuthorFactory;
use Tests\Mocks\Enums\AuthorTypeEnum;

Expand All @@ -27,4 +28,9 @@ public function country(): BelongsTo
{
return $this->belongsTo(Country::class);
}

public function books(): HasMany
{
return $this->hasMany(Book::class);
}
}
6 changes: 6 additions & 0 deletions tests/Mocks/Models/Country.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Tests\Mocks\Database\Factories\CountryFactory;

class Country extends Model
Expand All @@ -16,4 +17,9 @@ protected static function newFactory(): CountryFactory
{
return CountryFactory::new();
}

public function authors(): HasMany
{
return $this->hasMany(Author::class);
}
}
30 changes: 30 additions & 0 deletions tests/Mocks/Models/Flight.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Tests\Mocks\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Tests\Mocks\Database\Factories\FlightFactory;

class Flight extends Model
{
use HasFactory;

protected static $unguarded = true;

protected static function newFactory(): FlightFactory
{
return FlightFactory::new();
}

public function departure(): BelongsTo
{
return $this->belongsTo(Country::class);
}

public function arrival(): BelongsTo
{
return $this->belongsTo(Country::class);
}
}
53 changes: 53 additions & 0 deletions tests/Sorts/PowerJoins/RelationSortTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

use Spatie\QueryBuilder\AllowedSort;
use Spatie\QueryBuilder\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use TeamQ\QueryBuilder\Enums\JoinType;
use TeamQ\QueryBuilder\Sorts\RelationSort;
use Tests\Mocks\Models\Country;
use Tests\Mocks\Models\Flight;

beforeEach(function () {
$this->request = new Illuminate\Http\Request();
$this->request->setMethod(Request::METHOD_GET);

$belgium = Country::factory()->create(['name' => 'Belgium', 'code' => 'BE']);
$ecuador = Country::factory()->create(['name' => 'Ecuador', 'code' => 'EC']);

$this->firstFlight = Flight::factory()
->for($belgium, 'departure')
->for($ecuador, 'arrival')
->create([
'code' => '7485',
]);

$this->secondFlight = Flight::factory()
->for($ecuador, 'departure')
->for($belgium, 'arrival')
->create([
'code' => '8596',
]);
});

it('apply relationships using aliases that point to the same table', function () {
$this->request->query->add([
'sort' => 'departure.code',
]);

$queryBuilder = QueryBuilder::for(Flight::class, $this->request)
->allowedSorts([
AllowedSort::custom('departure.code', new RelationSort(JoinType::Inner, joinAliases: 'departure')),
AllowedSort::custom('arrival.code', new RelationSort(JoinType::Inner, joinAliases: 'arrival')),
]);

expect($queryBuilder->toSql())
->toBe(
'select `flights`.* from `flights` inner join `countries` as `departure` on `flights`.`departure_id` = `departure`.`id` order by `departure`.`code` asc'
)
->and($queryBuilder->get())
->sequence(
fn ($flight) => $flight->code->toBe('7485'),
fn ($flight) => $flight->code->toBe('8596'),
);
});
Loading
Loading