This is what is called polymorphic association. Doctrine can handle them with Inheritance>
So, you would define your base object, for example Author , and then you would have GroupAuthor and UserAuthor , which also extend this. Both of these must be configured as mapped classes based on Author . It is up to you to decide whether you choose a unidirectional table or class table inheritance; the end result will be the same.
The last thing to do is to associate the UserAuthor object with your User object and your GroupAuthor with your Group object.
Then you can use it something like this:
$author = $article->getAuthor(); if ($author instanceof UserAuthor) { $user = $author->getUser(); } elseif ($author instanceof GroupAuthor) { $group = $author->getGroup(); $users = $group->getUsers();
Edit: Display example
"parent" object, Author.php
/** * @ORM\Entity * @ORM\Table(name="authors") * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="type", type="string") * @ORM\DiscriminatorMap( {"user" = "UserAuthor", "group" = "GroupAuthor"} ) */ class Author { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /* any other shared fields... */ }
Display Entity, UserAuthor.php
class UserAuthor extends Author { }
etc.
source share