Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

symfony - Many-to-many self relation with extra fields?

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 :

/**
 * @ORMManyToMany(targetEntity="User", mappedBy="friends")
 */
protected $friendsWith;

/**
 * @ORMManyToMany(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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...