Doctrine DQL Delete from relation table

不问归期 提交于 2019-12-10 16:13:21

问题


Using Doctrine 2 and Symfony 2.0.

I have two Doctrine entities (let's suppose EntityA and EntityB).

I have a ManyToMany relation between them. So a EntityA_EntityB table has been created in database.

Using DQL or QueryBuilder, how can I delete from that relation table EntityA_EntityB?

Docrtine offers something like this to perform something similar:

->delete()
 ->from('EntityA a')
 ->where('a.id', '?', $id);

But I don't really get how to perform the deletion of row from the relation table.


回答1:


$em = ...; // instance of `EntityManager`

// fetch both objects if ID is known
$a = $em->getRepository("YourProjectNamespace:EntityA")->find($id_of_A);
$b = $em->getRepository("YourProjectNamespace:EntityB")->find($id_of_B);

// suppose you have `EntityA::getObjectsOfTypeB` which retrieves all of linked objects of type `EntityB`.
// This method return instacne of ArrayCollection
$a->getObjectsOfTypeB()->removeElement($b);
$em->flush();

Something like this?

Basically, you need to remove related object from collection rather than delete relation itself. you want to remove relation directly you can always use pure SQL, but in DQL that is not possible.

Raw DELETE SQL statement via DBAL Connection object

$conn = $this->getDoctrine()->getManager()->getConnection();
$stmt = $conn->prepare("DELETE FROM EntityAEntityB WHERE id_b IN (:ids_of_b)");
$stmt->bindParam('ids_of_b', $to_delete_ids); // BEWARE: this array has to have at least one element
$stmt->executeUpdate();


来源:https://stackoverflow.com/questions/20035069/doctrine-dql-delete-from-relation-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!