4

I am trying to develop a friends system, and I need a Many-To-Many relation on my User entities ; for now, this is what I've 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 some extra fields for these relations, for example the creation date or the state (accepted, pending, ...) ; I've created another entity "Friend", and I would like this entity to be used as a link between friends. But I don't really know how to manage this...

Do you have some ideas ?

Thanks !

Jérémy Dutheil
  • 6,099
  • 7
  • 37
  • 52

1 Answers1

9

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

Why are many-to-many associations less common? Because frequently you want to associate additional attributes with an association, in which case you introduce an association class. Consequently, the direct many-to-many association disappears and is replaced by one-to-many/many-to-one associations between the 3 participating classes.

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

I guess it should be Friend -> Special Association Class (with fileds: user_id, friend_id, date created) ->Friend. And you associate Friend to special class in two filed $myFriends and $imFriendOf :)

Wojciech Jasiński
  • 1,480
  • 2
  • 20
  • 42
  • But I don't really see the associations to make here. :/ User -> OneToMany -> Friend, Friend -> ManyToOne -> User ? There is no 3 classes, but only 2 here 'cause it's a self-association on User – Jérémy Dutheil Feb 03 '12 at 21:01
  • Ok I think I understand, it's basically the same idea but I just map to another class instead of directly User, isn't it ? – Jérémy Dutheil Feb 04 '12 at 08:59
  • That's right you have to map to 'association' class because doctrines association doesn't let you to add an extra filed to its 'association db table'. – Wojciech Jasiński Feb 04 '12 at 12:58