Doctrine DQL从关系表中删除 [英] Doctrine DQL Delete from relation table
问题描述
使用Doctrine 2和Symfony 2.0。
我有两个Doctrine实体(假设EntityA和EntityB)。
我们之间有一个ManyToMany关系。所以在数据库中创建了一个EntityA_EntityB表。
使用DQL或QueryBuilder,如何从该关系表中删除EntityA_EntityB?
Docrtine提供类似的东西来执行类似的操作:
- > delete()
- > from('EntityA a')
- > where('a.id','?',$ id);
但是我并没有真正了解如何从关系表中删除行。 p>
$ em = ...; // EntityManager的实例
//如果ID已知,则获取两个对象
$ a = $ em-> getRepository(YourProjectNamespace:EntityA) - > find($ id_of_A);
$ b = $ em-> getRepository(YourProjectNamespace:EntityB) - > find($ id_of_B);
//假设你有EntityA :: getObjectsOfTypeB,它检索所有类型为EntityB的链接对象。
//此方法返回ArrayCollection的实例
$ a-> getObjectsOfTypeB() - > removeElement($ b);
$ em-> flush();
这样的东西?
您需要从 collection
中删除相关对象,而不是删除关系本身。您要直接删除关系,您可以随时使用纯粹的 SQL
,但在 DQL
中是不可能的。
通过DBAL连接对象生成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:这个数组必须至少有一个元素
$ stmt-> executeUpdate();
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.
$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();
这篇关于Doctrine DQL从关系表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!