Doctrine2 check An object associated with OneToOne exists in the database

The entity has a declared relationship of OneToOne

/** * @var \Backend\SalesBundle\Entity\SalesOrder * * @ORM\OneToOne(targetEntity="Backend\CatalogBundle\Entity\CatalogProduct") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="product_id", referencedColumnName="product_id") * }) */ private $product; 

The following code will work in both cases. If an entry exists in the database, and if it does not

 {{ item.product.productId }} 

But when I call the field that should be loaded from the database, I have "Entity not found." an exception. All tests that I know are not suitable for checking this due to Doctrine Proxies

 {{ item.product.name }} {{ item.product is null }} {{ item.product is empty }} etc. 

Is there an elegant way to check if a related object exists? I can do it this way, but it's not enough for me because I need to call {{item.product.productId}}

 public function getProduct() { try { $sku = $this->product->getSku(); } catch (\Doctrine\ORM\EntityNotFoundException $e) { return null; } return $this->product; } 
+5
source share

Source: https://habr.com/ru/post/1201431/


All Articles