我尝试使用ManyToMany自引用更新数据库和控制器,问题是我没有错误,但MySQL在功能后没有更新,所以我无法弄清楚我是什么&# 39;我搞砸了。它没有任何意义。 有没有办法更新MySql或者至少要调试?
这是我的代码:
/**
* @ManyToMany(targetEntity="User")
* @JoinTable(name="friends",
* joinColumns={@JoinColumn(name="user_a_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="user_b_id", referencedColumnName="id")}
* )
* @var ArrayCollection
*/
private $friends;
/**
* Constructor.
*/
public function __construct()
{
$this->friends = new ArrayCollection();
}
/**
* @return array
*/
public function getFriends()
{
return $this->friends->toArray();
}
/**
* @param User $user
* @return void
*/
public function addFriend(User $user)
{
if (!$this->friends->contains($user)) {
$this->friends->add($user);
$user->addFriend($this);
}
}
/**
* @param User $user
* @return void
*/
public function removeFriend(User $user)
{
if ($this->friends->contains($user)) {
$this->friends->removeElement($user);
$user->removeFriend($this);
}
}
和我的控制器:
/**
* @Route("/addFriends")
*/
public function addFriends()
{
if (isset($_POST['add'])) {
$id = $_POST['id'];
$user = $this->getUser();
$friend = $this->getDoctrine()->getRepository(User::class)-
>find($id);
$user->addFriend($friend);
}
return $this->redirectToRoute('friends');
}
/**
* @Route("/removeFriends")
*/
public function removeFriends()
{
if (isset($_POST['add'])) {
$id = $_POST['id'];
$user = $this->getUser();
$friend = $this->getDoctrine()->getRepository(User::class)->find($id);
$user->removeFriend($friend);
}
return $this->redirectToRoute('friends');
}
答案 0 :(得分:0)
好的,所以我终于看到了我搞砸了,而且很简单,当我将一个用户添加到我的arrayCollection时,我的更改并没有保存,所以我很努力空数组,保存更改只需添加:
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
最后我的控制器看起来像这样:
public function addFriends(Request $request)
{
if (isset($request) && is_string($id = $request->get('id'))) {
$user = $this->getUser();
$friend = $this->getDoctrine()->getRepository(User::class)->find($id);
$user->addFriend($friend);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
return $this->redirectToRoute('friends');
}
希望这会对某人有所帮助!