Skip to content

Commit e7c87c7

Browse files
authored
Allow constraining relationship queries (#103)
* feat: allow constraining `ToMany` query * Run Prettier * chore: eloquent-specific relationships * Run Prettier --------- Co-authored-by: SychO9 <[email protected]>
1 parent 4c3b44f commit e7c87c7

File tree

5 files changed

+55
-1
lines changed

5 files changed

+55
-1
lines changed

src/Laravel/EloquentBuffer.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
use Illuminate\Database\Eloquent\Model;
77
use Illuminate\Database\Eloquent\Relations\MorphTo;
88
use Tobyz\JsonApiServer\Context;
9+
use Tobyz\JsonApiServer\Laravel\Field\ToMany;
10+
use Tobyz\JsonApiServer\Laravel\Field\ToOne;
911
use Tobyz\JsonApiServer\Schema\Field\Relationship;
1012

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

5860
if ($resource instanceof EloquentResource && !isset($constrain[$modelClass])) {
59-
$constrain[$modelClass] = fn($query) => $resource->scope($query, $context);
61+
$constrain[$modelClass] = function ($query) use (
62+
$resource,
63+
$context,
64+
$relationship,
65+
) {
66+
$resource->scope($query, $context);
67+
68+
if (
69+
($relationship instanceof ToMany ||
70+
$relationship instanceof ToOne) &&
71+
$relationship->scope
72+
) {
73+
($relationship->scope)($query, $context);
74+
}
75+
};
6076
}
6177
}
6278

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Tobyz\JsonApiServer\Laravel\Field\Concerns;
4+
5+
use Closure;
6+
7+
trait ScopesRelationship
8+
{
9+
public ?Closure $scope = null;
10+
11+
public function scope(?Closure $scope): static
12+
{
13+
$this->scope = $scope;
14+
15+
return $this;
16+
}
17+
}

src/Laravel/Field/ToMany.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
namespace Tobyz\JsonApiServer\Laravel\Field;
4+
5+
use Tobyz\JsonApiServer\Schema\Field\ToMany as BaseToMany;
6+
7+
class ToMany extends BaseToMany
8+
{
9+
use Concerns\ScopesRelationship;
10+
}

src/Laravel/Field/ToOne.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
namespace Tobyz\JsonApiServer\Laravel\Field;
4+
5+
use Tobyz\JsonApiServer\Schema\Field\ToOne as BaseToOne;
6+
7+
class ToOne extends BaseToOne
8+
{
9+
use Concerns\ScopesRelationship;
10+
}

src/Schema/Field/ToMany.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Tobyz\JsonApiServer\Schema\Field;
44

5+
use Closure;
56
use Tobyz\JsonApiServer\Context;
67
use Tobyz\JsonApiServer\Exception\BadRequestException;
78
use Tobyz\JsonApiServer\Exception\Sourceable;

0 commit comments

Comments
 (0)