簡體   English   中英

刪除Symfony實體中的所有相關子級

[英]Remove all related children in Symfony entity

假設我們有一個與ManyToMany關系的字段為

/**
* @var ArrayCollection
* 
* @ORM\ManyToMany(targetEntity="Users")
* @ORM\JoinTable(name="users_roles",
*      joinColumns={@ORM\JoinColumn(name="User_Id", referencedColumnName="id")},
*      inverseJoinColumns={@ORM\JoinColumn(name="Role_Id", referencedColumnName="id")})
*/
protected $userRole;

要從表中刪除一個相關元素,我們可以在實體中使用此功能:

/**
* Remove userRole
* @param \Acme\MyBundle\Entity\Users $user
*/
public function remvoveUserRole(\Acme\MyBundle\Entity\Users $user)
{
    $this->userRole->removeElement($user);
}

問題

ArrayCollection類型具有removeElement函數,該函數用於刪除關系中的一個元素。 還有另一個函數clear ,在api中表示清除集合,刪除所有元素 ,因此我可以在我的實體中使用下面的函數來清除所有相關元素,以便通過刷新將其全部刪除嗎?

/**
* Remove all user Roles
*/
public function remvoveAllUserRole()
{
    $this->userRole->clear();
}

它僅適用於ManyToMany相關表還是適用於ManyToOne?

Ţîgan Ion是正確的- removeElement / clear只從內存中刪除那些元素。

但是,我認為您可以實現一些接近的目標,具體取決於您在關系中如何配置cascadeorphanRemoval

$em = ...; // your EntityManager
$roles = $user->getRoles();
$roles->clear();
$user = $em->merge($user); // this is crucial
$em->flush();

為了使其正常工作,您需要將User關系配置為

  • cascade={"merge"} -這將使$em->merge()調用傳播到角色。
  • orphanRemoval = true因為這是@ManyToMany ,這將使EntityManager刪除自由懸掛的角色。

現在無法測試,但據我所知它可以工作。 明天我會嘗試一下,並在需要時更新答案。

希望這可以幫助...

注意: 此邏輯適用於ManyToMany關系,但不適用於ManyToOne

我測試了刪除特定用途的所有相關角色(ManyToMany)的方法,並且該方法有效。 您需要在UserEntity中將一個函數定義為

/**
* Remove all user Roles
*/
public function remvoveAllUserRole()
{
   $this->userRole->clear();
}

然后在您的控制器或其他任何位置(如果需要)中,您可以調用以下函數

$specificUser = $em->getRepository('MyBundle:Users')->findOneBy(array('username' => 'test user'));
if (!empty($specificUser)) {
   $specificUser->removeAllUserRole();
   $em->flush();
}

然后它將刪除測試用戶的所有相關角色,而我們不需要使用for循環並逐個刪除它們

如果我沒記錯的話,那是行不通的,您必須直接從數據庫中刪除arrayCollection中的“ role s”

$roles = $user->getRoles()
foreach $role from $roles 
           $em->remove($role);
$em->flush();

現在你應該得到一個空集合

ps:最好的方法是測試您的想法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM