symfony - Doctrine DQL 从关系表中删除

标签 symfony orm doctrine-orm dql

使用 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/

相关文章:

symfony - 对 Symfony 测试实践的困惑 : functional vs integration testing

php - JMSSerializerBundle 在 JSON 中返回 double 字符串

python - Django 在保留 ORM 的同时连接两个表

php - 在 Doctrine 中过滤 @OneToMany

caching - 使用 Symfony2,为什么缓存响应中的 ESI 标签会被忽略?

MySQL 位类型映射到哪种 Go 类型?

.net - 对整个层次结构使用单个表和不使用单个表的 ORM 示例?

php - doctrine 2 和 zend framework 2 如何使用缓存?

mysql - 与不是主键的外键(主键是 auto_increment 'id' )与doctrine2/symfony2 的 1-N 关系

javascript - 如何在 Symfony2 的 Bootstrap 模态弹出窗口中动态显示数据