Skip to content

Commit 04c4840

Browse files
author
Shashank Jain
committed
Fix: fix dynamically getting key name in request parser
1 parent 2903bc5 commit 04c4840

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/RequestParser.php

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Froiden\RestAPI\Exceptions\Parse\MaxLimitException;
99
use Froiden\RestAPI\Exceptions\Parse\NotAllowedToFilterOnThisFieldException;
1010
use Illuminate\Database\Eloquent\Relations\BelongsTo;
11+
use Illuminate\Database\Eloquent\Relations\HasMany;
1112
use Illuminate\Database\Eloquent\Relations\HasOne;
1213
use Illuminate\Support\Str;
1314

@@ -413,12 +414,28 @@ private function parseFields($fields)
413414

414415
if (Str::contains($fieldName, ".")) {
415416

416-
// TODO: add support for non standard relation column names for multi level relations
417+
$relationNameParts = explode('.', $fieldName);
418+
$model = $this->model;
419+
420+
$relation = null;
421+
422+
foreach ($relationNameParts as $rp) {
423+
$relation = call_user_func([ new $model(), $rp]);
424+
$model = $relation->getRelated();
425+
}
417426

418427
// Its a multi level relations
419428
$fieldParts = explode(".", $fieldName);
420429

421-
$singular = Str::singular(last($fieldParts));
430+
if ($relation instanceof BelongsTo) {
431+
$singular = $relation->getOtherKey();
432+
}
433+
else if ($relation instanceof HasOne || $relation instanceof HasMany) {
434+
$singular = explode('.', $relation->getForeignKey())[1];
435+
}
436+
else {
437+
$singular = Str::singular(last($fieldParts));
438+
}
422439

423440
// Unset last element of array
424441
unset($fieldParts[count($fieldParts) - 1]);
@@ -432,12 +449,12 @@ private function parseFields($fields)
432449
"limit" => config("api.defaultLimit"),
433450
"offset" => 0,
434451
"order" => "chronological",
435-
"fields" => [$singular . "_id"],
452+
"fields" => [$singular],
436453
"userSpecifiedFields" => true
437454
];
438455
}
439456
else {
440-
$this->relations[$parent]["fields"][] = $singular . "_id";
457+
$this->relations[$parent]["fields"][] = $singular;
441458
}
442459
}
443460
else {

0 commit comments

Comments
 (0)