Let's first describe my situation. I am using Symfony2 and I have a problem with a relationship between my entities.
I have two entities that are linked together. The two entities are AssociationQuestion
and AssociationPossibleAnswer
. I am currently creating a questionary software where one would have to link one possible answer on the left to another one possible answer on the right, such as in the following example:
Currently, I'm planning on having two attributes that are arrays in class AssociationQuestion
that would hold many AssociationPossibleAnswer
objects. The first array would contain the possible answers on the left and the second one would contain the possible answers on the right.
Therefore, to me, it looks like I would have two oneToMany relations in AssociationQuestion
AssociationQuestion:
oneToMany:
possibleAnswersLeft:
targetEntity: AssociationPossibleAnswer
mappedBy: associationQuestion
possibleAnswersRight:
targetEntity: AssociationPossibleAnswer
mappedBy: associationQuestion
Then, in AssociationPossibleAnswer
, I would have one ManyToOne relation :
AssociationPossibleAnswer:
manyToOne:
associationQuestion:
targetEntity: AssociationQuestion
The problem is that I get the following error trying to validate my doctrine. It seems that you can't have two entities linked to one as I would wish to do...
* The field AssociationQuestion#possibleAnswersLeft is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity AssociationPossibleAnswer#associationQuestion does not contain the required 'inversedBy=possibleAnswersLeft' attribute.
* The field AssociationQuestion#possibleAnswersRight is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity AssociationPossibleAnswer#associationQuestion does not contain the required 'inversedBy=possibleAnswersRight' attribute.
I'm wondering if this is the proper way to set my relation between my two entities. Is it possible to have two attributes pointing to an entity while in return the entity does not know which attribute it is being pointed from.
This case cannot be solved with OneToMany associations.
You need 2 distinct relations between
AssociationQuestion
andAssociationPossibleAnswer
. The way you've set it up, you only have 1 relation. Just look at the 1 ManyToOne association you created inAssociationPossibleAnswer
.And you're trying to have 2 opposite sides of that 1 relation, which is theoretically impossible. A relation can only have 2 endpoints (not 3).
Solution
Implement 2 (unidirectional) ManyToMany associations in
AssociationQuestion
, and make the foreign key pointing toAssociationPossibleAnswer
unique:Doctrine calls this a One-To-Many, Unidirectional with Join Table association.