Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 Check if related entity exists

I'm really tired to figuring out how I can check in Doctrine 2 if related entity record exists in DB. Help me please.

For example I have two entities. One is the order status of certain delivery company. Another one is order.

Order.php

/**
 * @ORM\OneToOne(targetEntity="Application\DeliveryBundle\Entity\DpdOrderStatus", mappedBy="order")
 * @var DpdOrderStatus
 */
$dpdOrderStatus;

DpdOrderStatus.php

/**
 * @ORM\Id
 * @ORM\OneToOne(targetEntity="\Application\FrontendBundle\Entity\Order", inversedBy="dpdOrderStatus")
 * @ORM\JoinColumn(onDelete="CASCADE")
 * @var Order
 */
$order;

Order entity sometimes doesn't have status and I need to check if it has.

AFAIK if I will try to use is_null($order->getDpdOrderStatus()) it will always be false because Doctrine always create Proxy objects for its entities if EAGER mode is not specified.

So what is the most proper way to check if my status entity exists in database?

like image 779
alexey_detr Avatar asked Aug 05 '13 07:08

alexey_detr


1 Answers

Add a method that checks if the order has an order status:

Order.php

public function hasOrderStatus(){
 return ! is_null($this->dpdOrderStatus);
}

More information: Techniques to check if relationship exists in Doctrine2

like image 122
zizoujab Avatar answered Sep 20 '22 18:09

zizoujab