使用 Doctrine 2 和 Symfony 2.0。
我有两个 Doctrine 实体(假设 EntityA 和 EntityB)。
我在它们之间有一个多对多的关系。所以在数据库中创建了一个 EntityA_EntityB 表。
使用 DQL 或 QueryBuilder,如何从该关系表 EntityA_EntityB 中删除?
Docrtine 提供了这样的东西来执行类似的事情:
->delete()
->from('EntityA a')
->where('a.id', '?', $id);
但我真的不知道如何从关系表中删除行。
最佳答案
$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();
像这样的东西?
基本上,您需要从
collection
中删除相关对象而不是删除关系本身。你想直接删除关系你总是可以使用纯 SQL
,但在 DQL
这是不可能的。通过 DBAL Connection 对象的原始 DELETE SQL 语句
$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();
关于symfony - Doctrine DQL 从关系表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20035069/