Skip to content

Commit

Permalink
Allow constraining relationship queries (#103)
Browse files Browse the repository at this point in the history
* feat: allow constraining `ToMany` query

* Run Prettier

* chore: eloquent-specific relationships

* Run Prettier

---------

Co-authored-by: SychO9 <[email protected]>
  • Loading branch information
SychO9 and SychO9 authored Mar 31, 2024
1 parent 4c3b44f commit e7c87c7
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/Laravel/EloquentBuffer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Laravel\Field\ToMany;
use Tobyz\JsonApiServer\Laravel\Field\ToOne;
use Tobyz\JsonApiServer\Schema\Field\Relationship;

abstract class EloquentBuffer
Expand Down Expand Up @@ -56,7 +58,21 @@ public static function load(
$modelClass = get_class($resource->newModel($context));

if ($resource instanceof EloquentResource && !isset($constrain[$modelClass])) {
$constrain[$modelClass] = fn($query) => $resource->scope($query, $context);
$constrain[$modelClass] = function ($query) use (
$resource,
$context,
$relationship,
) {
$resource->scope($query, $context);

if (
($relationship instanceof ToMany ||
$relationship instanceof ToOne) &&
$relationship->scope
) {
($relationship->scope)($query, $context);
}
};
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/Laravel/Field/Concerns/ScopesRelationship.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Tobyz\JsonApiServer\Laravel\Field\Concerns;

use Closure;

trait ScopesRelationship
{
public ?Closure $scope = null;

public function scope(?Closure $scope): static
{
$this->scope = $scope;

return $this;
}
}
10 changes: 10 additions & 0 deletions src/Laravel/Field/ToMany.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Tobyz\JsonApiServer\Laravel\Field;

use Tobyz\JsonApiServer\Schema\Field\ToMany as BaseToMany;

class ToMany extends BaseToMany
{
use Concerns\ScopesRelationship;
}
10 changes: 10 additions & 0 deletions src/Laravel/Field/ToOne.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Tobyz\JsonApiServer\Laravel\Field;

use Tobyz\JsonApiServer\Schema\Field\ToOne as BaseToOne;

class ToOne extends BaseToOne
{
use Concerns\ScopesRelationship;
}
1 change: 1 addition & 0 deletions src/Schema/Field/ToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tobyz\JsonApiServer\Schema\Field;

use Closure;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\Sourceable;
Expand Down

0 comments on commit e7c87c7

Please sign in to comment.