Skip to content

Commit c047a0f

Browse files
author
Marius
committed
add withRelationsCount and withRelationsExistence on get
1 parent 2620cee commit c047a0f

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ The above "errors" are optional and appear only for validation errors while "mes
180180

181181

182182
#### III.2 Get resource
183-
**GET** /{resource}/{identifier}?withRelations[]=has_many_relation&withRelations[]=has_one_relation
183+
**GET** /info/{resource}/{identifier}?withRelations[]=has_manyRelation&withRelations[]=has_oneRelation&withRelationsCount[]=has_manyRelation&withRelationsExistence[]=has_manyRelation
184184

185185
headers:
186186

@@ -211,6 +211,8 @@ Json Response:
211211
}
212212
}
213213
],
214+
"has_manyRelation_count": 0,
215+
"has_manyRelation_exist": false,
214216
}
215217

216218
400:

src/Http/Controllers/ResourceControllerTrait.php

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,27 @@ public function get(string $identifier, Request $request): JsonResponse
9999
{
100100
try {
101101
$this->throwIfForbidden($this->forbidGet);
102+
$baseModel = $this->resourceService->get(
103+
$identifier,
104+
$this->getFilteredRelations((array)$request->get('withRelations'))
105+
);
106+
$result = $baseModel->toArray();
107+
$countRelations = $this->getFilteredRelations((array)$request->get('withRelationsCount'));
108+
109+
foreach ($countRelations as $relationName) {
110+
$result[$relationName . ListFilterBuilder::COUNT_ALIAS_POSTFIX] ??=
111+
$baseModel->{$relationName}()->count();
112+
}
113+
114+
foreach ($this->getFilteredRelations((array)$request->get('withRelationsExistence')) as $relationName) {
115+
$result[$relationName . '_exist'] ??= \in_array($relationName, $countRelations, true) &&
116+
\is_int($result[$relationName . ListFilterBuilder::COUNT_ALIAS_POSTFIX] ?? null) ?
117+
$result[$relationName . ListFilterBuilder::COUNT_ALIAS_POSTFIX] > 0 :
118+
$baseModel->{$relationName}()->exists();
119+
}
102120

103121
return GeneralHelper::app(JsonResponse::class, [
104-
'data' => $this->resourceService->get(
105-
$identifier,
106-
$this->getFilteredRelations((array)$request->get('withRelations'))
107-
)->toArray(),
122+
'data' => $result,
108123
'status' => 200
109124
]);
110125
} catch (\Throwable $e) {

0 commit comments

Comments
 (0)