Doctrine DQL Remove from relationship table

Using Doctrine 2 and Symfony 2.0.

I have two Doctrine objects (suppose EntityA and EntityB).

I have a ManyToMany relationship between them. Therefore, the EntityA_EntityB table was created in the database.

Using DQL or QueryBuilder, how can I remove EntityA_EntityB from this relationship table?

Docrtine offers something like this to accomplish something like this:

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

But I really don't understand how to delete a row from a relationship table.

+4
source share
1 answer
$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 that?

, collection, . , SQL, DQL .

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();
+3

All Articles