Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

symfony - Getting a "true" object from a proxy object in doctrine2

Doctrine uses proxy objects to represent related objects in order to facilitate lazy loading. This is a really cool feature, but its causing an issue with something I am trying to accomplish.

I have customized my user object so that they are all required to be related to a different object, which I will call city. This relationship is working fine.

I have a form that my user fills out to generate another object, street. Street is also related to the city object. Instead of having my user select the city when they fill out the form, I want to automatically set it before I persist the object to my database.

I tried using $event->setCity($user->getCity()), but since $user->getCity() returns a proxy object, this generates an error. Is there a function I can call from the proxy object to get the real one?

Note: I am aware I can create a custom query with a join to force doctrine to actually load the related object, but since this is the user (using FOSUserBundle) that would be difficult to do properly.

question from:https://stackoverflow.com/questions/8337754/getting-a-true-object-from-a-proxy-object-in-doctrine2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is unlikely to help in the specific instance for the question, since you're relying on a third-party module, but you can prevent the lazy loading by setting the "fetch mode" for your entity to "EAGER".

User:
    ManyToOne:
        city:
            fetch: EAGER

This can also be handled by annotations:

@ManyToOne(targetEntity="city", fetch="EAGER")
@JoinColumn(name="city", referencedColumnName="id")

See http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-manytoone

None of the other answers I've seen here worked for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...