Do-it-yourself multi-to-many relationships with optional fields?

I'm trying to create a friends system, and I need a Many-to-Many relationship to User objects; at the moment this is what i have done:

/** * @ORM\ManyToMany(targetEntity="User", mappedBy="friends") */ protected $friendsWith; /** * @ORM\ManyToMany(targetEntity="User", inversedBy="friendsWith") * @JoinTable(name="friends", * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, * inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")} * ) */ protected $friends; 

But I would like to have additional fields for this relationship, for example, the date of creation or the state (accepted, pending, ...); I created another Friend object, and I would like this object to be used as a link between friends. But I do not know how to do this ...

Do you have any ideas?

Thanks!

+4
source share
1 answer

I'm afraid you need an extra class to create such an association. Here is a tip from the doctrine documentation:

Why are many-to-many associations less common? Because often you want to associate additional attributes with an association in which if you enter an association class. Consequently, the direct many-to-many association disappears and the one-to-many / many-one association between the three participating classes is replaced.

http://www.doctrine-project.org/docs/orm/2.1/en/reference/association-mapping.html#many-to-many-unidirectional

I assume it should be Friend -> Special Association Class (with names: user_id, friend_id, creation date) -> Friend. And you join the Friend to a special class in the two filed $ myFriends and $ imFriendOf :)

+8
source

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


All Articles