I’m having a little problem with a possible multiple relationship in one field in Doctrine 2. For example, i have an Article entity with one field called author. This field is a ManyToOne to the User entity. However, this field can also relate to the Group entity. So, how the hell can i create such schema?
I have considered creating a new entity, called ArticleAuthor which has two fields: user and group, and depending on form input, i populate one of the fields. This way, this table ArticleAuthor holds it’s own id and the proper relationship to the correct table. Is this a correct approach?
This is what’s referred to as a polymorphic association. Doctrine is able to handle these using Inheritance Mapping
So you’d define your base entity, such as
Author, and then you’d have aGroupAuthorand aUserAuthorwhich both extend this. These both need to be configured as mapped classes on the baseAuthorentity. It’s up to you whether you opt for single table or class table inheritance; the end result would be the same.The last thing to do is to associate the
UserAuthorentity to yourUserentity, and yourGroupAuthorto yourGroupentity.Then you’d be able to use it somewhat like this:
Edit: Example mapping
The ‘parent’ entity,
Author.phpMapped entity,
UserAuthor.phpetc