根据post 使用Doctrine在Symfony2.1中实现好友列表,我实现了@Roberto Trunfio的解决方案。
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="friends")
*/
private $friendsWithMe;
/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
* @ORM\JoinTable(name="friends",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
*/
private $friends;它起作用了,不过我想更进一步,添加额外的字段,如“发件人、接收者、状态、sendingDate.”但我不知道怎么整合它。有人能帮帮我吗?谢谢
发布于 2016-06-14 09:20:40
如果要用其他属性装饰关联,则需要一个关联类。从文件中 (向下滚动一点):
为什么多到多的协会不那么普遍?因为通常您希望将其他属性与关联相关联,在这种情况下,需要引入关联类。因此,直接的多到多关联消失了,取而代之的是三个参与阶层之间的一对多/多对一的关联。
你的例子中的关联类是友谊。一个用户可以有很多朋友,一个用户可以是许多用户的朋友。或者更严格地说:一个用户有很多友谊,很多友谊映射给一个朋友。在下面给出的示例中,Friendship具有附加属性$hasBeenHelpful (确实是不对称的)。
// src/AppBundle/Entity/User.php
/**
* @ORM\Entity
*/
class User
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* The people who I think are my friends.
*
* @ORM\OneToMany(targetEntity="Friendship", mappedBy="user")
*/
private $friends;
/**
* The people who think that I’m their friend.
*
* @ORM\OneToMany(targetEntity="Friendship", mappedBy="friend")
*/
private $friendsWithMe;
// …
}和友谊协会:
// src/AppBundle/Entity/Friendship.php
/**
* @ORM\Entity
*/
class Friendship
{
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="friends")
* @ORM\Id
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="friendsWithMe")
* @ORM\Id
*/
private $friend;
/**
* Example of an additional attribute.
*
* @ORM\Column(type="boolean")
*/
private $hasBeenHelpful;
// …
}您可能希望向用户类添加一些函数,例如
<?php
use Doctrine\Common\Collections\ArrayCollection;
class User
{
public function __construct()
{
$this->friends = new ArrayCollection();
$this->friendsWithMe = new ArrayCollection();
}
public function addFriendship(Friendship $friendship)
{
$this->friends->add($friendship);
$friendship->friend->addFriendshipWithMe($friendship);
}
public function addFriendshipWithMe(Friendship $friendship)
{
$this->friendsWithMe->add($friendship);
}
public function addFriend(User $friend)
{
$fs = new Friendship();
$fs->setUser($this);
$fs->setFriend($friend);
// set defaults
$fs->setHasBeenUseful(true);
$this->addFriendship($fs);
}
}https://stackoverflow.com/questions/37797186
复制相似问题