I have three entities: User, Answer, and Question.
There is a OneToMany relationship between User and Answer and a ManyToOne relationship between Answer and Question. Basically, a particular user optionally gives answers to a bunch of questions.
What I’m trying to accomplish in the world of ORM is retrieving ALL questions and their associated answers for a particular user. The key part is that a user may not have answered a particular question but I still want to get that question (with a null answer).
My Answer entity has a ‘user’ field which maps to the User entity which is inverted by an ‘answers’ field within the User entity. If I use this ‘answers’ field within the User entity, I only get the question/answer pairs for which the user has actually answered. I do not get questions for which the user has not answered.
Typically, using raw SQL, this would involve a simple “left outer join” between my question and answer table, but I want this to be done using Doctrine’s ORM. Any suggestions? I’m pretty new to the world of ORM.
I did it! Here’s how:
I created a field in my
Questionentity that contains all answers, from all users, for that particular question; its mapped with a OneToMany relationship to theAnswerentity. And then to make sure we restrict that list to the answers for a particular user I created a custom repository for myQuestionentity and created the following function:Just pass in an instance of the
Userentity, and voila!