@@ -27,19 +27,27 @@ final class ModelInspector
2727{
2828 private ?ClassReflector $ modelClass ;
2929
30- public function __construct (
31- private object | string $ model ,
32- )
30+ private object | string $ model ;
31+
32+ public function __construct ( object | string $ model )
3333 {
34- if ($ this ->model instanceof ClassReflector) {
35- $ this ->modelClass = $ this ->model ;
34+ if ($ model instanceof HasMany) {
35+ $ model = $ model ->property ->getIterableType ()->asClass ();
36+ $ this ->modelClass = $ model ;
37+ } elseif ($ model instanceof BelongsTo || $ model instanceof HasOne) {
38+ $ model = $ model ->property ->getType ()->asClass ();
39+ $ this ->modelClass = $ model ;
40+ } elseif ($ model instanceof ClassReflector) {
41+ $ this ->modelClass = $ model ;
3642 } else {
3743 try {
38- $ this ->modelClass = new ClassReflector ($ this -> model );
44+ $ this ->modelClass = new ClassReflector ($ model );
3945 } catch (ReflectionException ) {
4046 $ this ->modelClass = null ;
4147 }
4248 }
49+
50+ $ this ->model = $ model ;
4351 }
4452
4553 public function isObjectModel (): bool
@@ -247,13 +255,12 @@ public function resolveRelations(string $relationString, string $parent = ''): a
247255 $ currentRelationName ,
248256 ), '. ' );
249257
250- return [
251- $ currentRelation ,
252- ...model ($ currentRelation ->property ->getType ()->asClass ())->resolveRelations ($ newRelationString , $ newParent )
253- ];
258+ $ relations = [$ currentRelation ];
259+
260+ return [...$ relations , ...model ($ currentRelation )->resolveRelations ($ newRelationString , $ newParent )];
254261 }
255262
256- public function getEagerRelations ( ): array
263+ public function resolveEagerRelations ( string $ parent = '' ): array
257264 {
258265 if (! $ this ->isObjectModel ()) {
259266 return [];
@@ -262,8 +269,26 @@ public function getEagerRelations(): array
262269 $ relations = [];
263270
264271 foreach ($ this ->modelClass ->getPublicProperties () as $ property ) {
265- if ($ property ->hasAttribute (Eager::class)) {
266- $ relations [$ property ->getName ()] = $ this ->getRelation ($ property );
272+ if (! $ property ->hasAttribute (Eager::class)) {
273+ continue ;
274+ }
275+
276+ $ currentRelationName = $ property ->getName ();
277+ $ currentRelation = $ this ->getRelation ($ currentRelationName );
278+
279+ if (! $ currentRelation ) {
280+ continue ;
281+ }
282+
283+ $ relations [$ property ->getName ()] = $ currentRelation ->setParent ($ parent );
284+ $ newParent = ltrim (sprintf (
285+ '%s.%s ' ,
286+ $ parent ,
287+ $ currentRelationName ,
288+ ), '. ' );
289+
290+ foreach (model ($ currentRelation )->resolveEagerRelations ($ newParent ) as $ name => $ nestedEagerRelation ) {
291+ $ relations [$ name ] = $ nestedEagerRelation ;
267292 }
268293 }
269294
0 commit comments