How to bulk remove entities in a ManyToMany relationship in Doctrine 2?
Asked Answered
C

1

8

Say I have the following classes:

class Store
{
    /**
     * @ManyToMany(targetEntity="PaymentMethod")
     */
    protected $paymentMethods;
}

class PaymentMethod
{
}

When we delete (or just disable, without actually removing from the database) a PaymentMethod, we'd like that this paymentMethod gets removed from all the Store::$paymentMethods collections.

Up to now, we've been using raw SQL queries on the junction table for this:

DELETE FROM StorePaymentMethod WHERE paymentMethodId = ?

Is there a way to do that in Doctrine, preferably in DQL?

Caspar answered 10/2, 2012 at 10:47 Comment(2)
let me get this straight. you want to remove the deleted payment methods from the list in Store class? deleting it from the DB won't remove it from the list.Indignity
If it is a many to many, can you not just set the $stores collection in PaymentMethod to an empty collection and persist it? You would need to invalidate all Store objects in memory to ensure that their reciprocal links did not keep the records. Though in an ideal world, the accessors methods you write to perform the empty would go through the Stores removing the reciprocal links.Studied
T
-3

Something along these lines ?

$qb = $em->createQueryBuilder();

$qb->delete('StorePaymentMethod', 'spm')
   ->where('spm.paymentMethodId = : paymentMethodId')
   ->setParameter('paymentMethodId', $id);

return $qb->getQuery()->getResult();
Toothwort answered 8/3, 2012 at 12:21 Comment(1)
StorePaymentMethod is not an entity, that's just the join table. So in DQL it has no meaning unfortunately!Caspar

© 2022 - 2024 — McMap. All rights reserved.