Home » Php » php – How to bulk remove entities in a ManyToMany relationship in Doctrine 2?

php – How to bulk remove entities in a ManyToMany relationship in Doctrine 2?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

Something along these lines ?

$qb = $em->createQueryBuilder();

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

return $qb->getQuery()->getResult();