我一直想把这个弄清楚2个小时,我似乎无法理解出了什么问题。
我正在使用Symfony2和FOSUserBundle。
我创建了一个扩展FOSUserBundle的BaseUser类的User实体。在这个用户实体中,我有3个变量,id,my_mentors和my_mentees。更多详情如下:
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="my_mentees")
*/
protected $my_mentors;
/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="my_mentors")
* @ORM\JoinTable(name="mentor_and_mentee_relationship",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="mentors_or_mentees_user_id", referencedColumnName="id")}
* )
*/
protected $my_mentees;
public function __construct()
{
parent::__construct();
$this->my_mentors = new ArrayCollection();
$this->my_mentees = new ArrayCollection();
}
public function __toString()
{
return $this->getUsername();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add my_mentors
*
* @param Fitness\FitBundle\Entity\User $myMentors
*/
public function addUser(\Fitness\FitBundle\Entity\User $myMentors)
{
$this->my_mentors[] = $myMentors;
}
/**
* Get my_mentors
*
* @return Doctrine\Common\Collections\Collection
*/
public function getMyMentors()
{
return $this->my_mentors;
}
/**
* Get my_mentees
*
* @return Doctrine\Common\Collections\Collection
*/
public function getMyMentees()
{
return $this->my_mentees;
}
}
我创建了自引用,因为Mentee(用户)将订阅Mentor(也是用户)。我尝试使用以下函数执行此操作:
public function subscribeAction($menteeID, $mentorID)
{
$em = $this->getDoctrine()
->getEntityManager();
$mentor = $em->getRepository('TestBundle:User')
->find($mentorID);
$mentee = $em->getRepository('TestBundle:User')
->find($menteeID);
$currentMentors = $mentee->getMyMentors();
if ($currentMentors->contains($mentor))
$this->get('session')->setFlash('subscribe-notice', 'You have already signed up to this mentor!');
else
{
$mentee->setIsMentor(false);
$mentee->addUser($mentor);
$mentor->addUser($mentee);
$em->persist($mentee);
$em->persist($mentor);
$em->flush();
$this->get('session')->setFlash('subscribe-notice', 'Subscription succesful!');
}
return $this->redirect($this->generateUrl('TestBundle_testpage', array('id' => $mentor->getMentorProfile()->getId()) ));
}
这里的问题是,当我检查数据库时,它不会保留数据。导师 - 被指导者关系信息不存储在注释声明的“mentor_and_mentee_relationship”表中。
我坚持让$导师和$ mentee试图让它发挥作用,但显然它没有。
我的ORM注释是否可能被错误地声明?
答案 0 :(得分:0)
您正在使用相同的功能(addUser)添加指导者并添加受指导者。这是错的。首先,您需要在实体中使用两个不同的setter(我更改了addUser的名称以使其清晰)
/**
* Add my_mentors
*
* @param Fitness\FitBundle\Entity\User $myMentors
*/
public function addMentor(\Fitness\FitBundle\Entity\User $myMentors)
{
$this->my_mentors[] = $myMentors;
}
/**
* Add my_mentees
*
* @param Fitness\FitBundle\Entity\User $myMentees
*/
public function addMentee(\Fitness\FitBundle\Entity\User $myMentees)
{
$this->my_mentees[] = $myMentees;
}
然后在你的控制器中执行:
$mentee->addMentor($mentor);
$mentor->addMentee($mentee);