How Symfony and Doctrine fetches associations and related entities

大兔子大兔子 提交于 2019-12-12 03:58:40

问题


I cracked my head trying to realize how Symfony and Doctrine fetch associated entities.

Lets imagine: i have several associated entities:

  • Company (ManyToOne to City)
  • City (ManyToOne to Region, OneToMany to Company)
  • Region (ManyToOne to Country, OneToMany to City)
  • Country (OneToMany to Region)

When i render Company form i create Form Event Listener (on PRE_SET_DATA) that inserts Region and Country selectboxes to this form. The values in these fields must be set according to associated Region.

I retrieve current Company Region via:

$company = $event->getData();
$city = $company->getCity()

That works good

But when i try this:

$region = $city->getRegion(); // returns NULL
$country = $region->getCountry(); // returns NULL

these methods returns NULL. But in fact all associations exists and Doctrine association mapping is correct. Why?

According to Doctrine documentation: when i call getter for the proxy object (these ovjects are proxies, right?) - Doctrine should fetch insufficient data from database and update the object. In fact - methods return NULLs.

How can i get any associated entity? (from any association deep level)


回答1:


I just needed to remove cache dir...




回答2:


you should try to get it from your controller instead of the Form Class

  • $em = $this->getDoctrine()->getManager();
  • $em->initializeObject($obj);//this will initialize the object you need and fetch the real one from the database and not the proxy class Doctrine returns.

It's returning NULL because it has too many levels company->(1)city->(2)region and the doctrine get lost with the proxy class. if this doesn't work, try to make a DLQ query when you have the city.

if you want to understand how a proxy class looks like dump($company); and you will see that it only show the id of city.



来源:https://stackoverflow.com/questions/32779178/how-symfony-and-doctrine-fetches-associations-and-related-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!