Created
May 22, 2024 13:24
-
-
Save rela589n/a38ac8d34acf8778a4e994dd4985bb9a to your computer and use it in GitHub Desktop.
Manually initializing relationship on doctrine entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// warning: this approach is error-prone in case if there's a doctrine's lazy-entity proxy! | |
// when trying to call getQuestion() method on such non-initialized object, "property not initialized" error will come up | |
trait ManyToOneOtherEntityRelationshipMappingTrait | |
{ | |
protected Question $question; | |
#[ORM\Column(type: 'uuid')] | |
private Uuid $questionId; | |
/** @internal */ | |
#[ORM\PostLoad] | |
public function hydrateQuestion(PostLoadEventArgs $eventArgs): void | |
{ | |
$objectManager = $eventArgs->getObjectManager(); | |
/** @var ?Question $question */ | |
$question = $objectManager->find(Question::class, $this->questionId); | |
if (null === $question) { | |
throw new LogicException(sprintf('Question not found: %s', $this->questionId->toRfc4122())); | |
} | |
$this->question = $question; | |
} | |
/** @internal */ | |
#[ORM\PreFlush] | |
public function deHydrateQuestion(): void | |
{ | |
$questionId = $this->question->getId(); | |
if (isset($this->questionId) && $this->questionId->equals($questionId)) { | |
return; | |
} | |
$this->questionId = $questionId; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment