From 674f0502c43481caa8b58b696832f90b57b6f2f5 Mon Sep 17 00:00:00 2001 From: gramparallelo Date: Thu, 18 Jun 2020 10:22:00 -0700 Subject: [PATCH] Nested Relationship with includeRelationship Method --- src/TransformBuilder.php | 14 ++++++++++++++ src/Transformers/Concerns/HasRelationships.php | 10 ++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/TransformBuilder.php b/src/TransformBuilder.php index cb1816f..2501091 100644 --- a/src/TransformBuilder.php +++ b/src/TransformBuilder.php @@ -313,6 +313,20 @@ protected function eagerLoadRelations($data, array $requested, $transformer) return $eagerLoads; } + // Note, currently only works one level deep for now, ex. 'comments.user' + // Note, $transformer->relations must have transformer associated with each relation even if parent as includeRelation method + // because this is how we check the nested transformer, + // method_exists($transformer->relations[$parent], 'include' . ucfirst($nestedRelation)) + $nestedRelations = explode('.', $identifier); + if (count($nestedRelations) > 1) { + $parent = $nestedRelations[0]; + $nestedRelation = last($nestedRelations); + + if (method_exists($transformer->getRelations()[$parent], 'include' . ucfirst($nestedRelation))) { + return $eagerLoads; + } + } + return array_merge($eagerLoads, [$identifier => $requested[$relation] ?: function () { }]); }, []); diff --git a/src/Transformers/Concerns/HasRelationships.php b/src/Transformers/Concerns/HasRelationships.php index 40b2d4a..a7c8381 100644 --- a/src/Transformers/Concerns/HasRelationships.php +++ b/src/Transformers/Concerns/HasRelationships.php @@ -29,6 +29,16 @@ trait HasRelationships */ protected $load = []; + /** + * Get list of available relations. + * + * @return array + */ + public function getRelations(): array + { + return $this->relations; + } + /** * Get a list of whitelisted relations that are requested, including nested relations. *