From 3d6315834a37b1c2f227ef0f5b05eddaac9b7465 Mon Sep 17 00:00:00 2001 From: Maxim Babichev Date: Wed, 27 Apr 2022 00:29:01 +0300 Subject: [PATCH] eager loading fix --- src/Traits/MorphOneWallet.php | 17 +++++++++++++++++ tests/Units/Domain/EagerLoadingTest.php | 3 +-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Traits/MorphOneWallet.php b/src/Traits/MorphOneWallet.php index f15561baf..da91c6d4a 100644 --- a/src/Traits/MorphOneWallet.php +++ b/src/Traits/MorphOneWallet.php @@ -42,4 +42,21 @@ public function wallet(): MorphOne }) ; } + + public function getWalletAttribute(): ?WalletModel + { + $wallet = $this->getRelationValue('wallet'); + if ($wallet === null) { + return null; + } + + assert($wallet instanceof WalletModel); + + if (!$wallet->relationLoaded('holder')) { + $holder = app(CastServiceInterface::class)->getHolder($this); + $wallet->setRelation('holder', $holder); + } + + return $wallet; + } } diff --git a/tests/Units/Domain/EagerLoadingTest.php b/tests/Units/Domain/EagerLoadingTest.php index 51985a517..359350cf4 100644 --- a/tests/Units/Domain/EagerLoadingTest.php +++ b/tests/Units/Domain/EagerLoadingTest.php @@ -35,8 +35,7 @@ public function testUuidDuplicate(): void $balances = []; foreach ($buyers as $buyer) { self::assertTrue($buyer->relationLoaded('wallet')); - // self::assertTrue($buyer->wallet->relationLoaded('holder')); - // fixme: I did not find a way to load the buyer, maybe someday I will get there. + self::assertTrue($buyer->wallet->relationLoaded('holder')); $uuids[] = $buyer->wallet->uuid; $balances[] = $buyer->wallet->balanceInt;