我需要建议您如何处理这种情况:
我有两个实体:
客户和预订。 客户拥有唯一的电话号码。
然后我有一个表格,用户可以在其中选择日期,并且必须提供姓名,电话号码,电子邮件之类的信息。
如果电话号码存在于数据库中,则应该找到该记录并使用它,而不是尝试创建新记录并抛出UniqueConstraintViolationException
。
现在我在EventListener中处理它:
public function prePersist(LifecycleEventArgs $args): void
{
$this->em = $args->getEntityManager();
$this->reserve($args);
}
private function reserve(LifecycleEventArgs $args): void
{
$reservation = $args->getEntity();
if ($reservation instanceof Reservation) {
$this->reservation = $reservation;
$this->email = $this->getEmail();
$this->phoneNumber = $this->getInternationalNumber();
//check if customer is new
$this->setCustomer();
}
}
private function setCustomer(): void
{
$customerRepository = $this->em->getRepository(Customer::class);
if ($customer = $customerRepository->findOneBy(['phoneNumber' => $reservation->getCustomer()->getPhoneNumber()])) {
$this->reservation->setCustomer($customer);
}
}
您将如何处理?我认为应该有一个更好的方法(也许?)。