Working with multiple relationships in one field in Doctrine 2

I have a little problem with possible multiple linking in one field in Doctrine 2. For example, I have an Article object with one field called author . This field is ManyToOne for the User object. However, this field may also refer to a Group object. So how the hell can I create such a circuit?

I considered creating a new object called ArticleAuthor , which has two fields: User and Group , and depending on the form input, I fill out one of the fields. Thus, this ArticleAuthor table contains its own id and the correct relation to the correct table. Is it correct?

+4
source share
1 answer

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(); // Not sure if you'd need this? } 

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

 /** * @ORM\Entity * @ORM\Table(name="user_authors") */ class UserAuthor extends Author { /* All columns unique to the UserAuthor entity... */ } 

etc.

+6
source

Source: https://habr.com/ru/post/1440824/


All Articles