Search code examples
phpsymfonydoctrine-ormdql

Delete row from related entity in many to many relationship in Doctrine2


I have this entity:

class FabricanteProductoSolicitud
{
    use IdentifierAutogeneratedEntityTrait;

    /**
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\FabricanteDistribuidor")
     * @ORM\JoinColumn(name="fabricante_distribuidor_id", referencedColumnName="id")
     */
    protected $fabricante_distribuidor;

    /**
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\ProductoSolicitud")
     * @ORM\JoinColumn(name="producto_solicitud_id", referencedColumnName="id")
     */
    protected $producto_solicitud;

    /**
     * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\Pais", inversedBy="fabricanteProductoSolicitudPais", cascade={"persist"})
     * @ORM\JoinTable(name="nomencladores.pais_fabricante_producto_solicitud", schema="nomencladores",
     *      joinColumns={@ORM\JoinColumn(name="fabricante_producto_solicitud_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="pais_id", referencedColumnName="id")}
     * )
     */
    protected $paisesFabricanteProductoSolicitudPais;

    /**
     * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\ModeloMarcaProducto", inversedBy="modeloMarcaProducto", cascade={"persist"})
     * @ORM\JoinTable(name="negocio.fabricante_modelo_marca_producto", schema="negocio",
     *      joinColumns={@ORM\JoinColumn(name="fabricante_producto_solicitud_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="modelo_marca_producto_id", referencedColumnName="id")}
     * )
     */
    protected $modeloMarcaProducto;

    public function __construct()
    {
        $this->paisesFabricanteProductoSolicitudPais = new ArrayCollection();
        $this->modeloMarcaProducto = new ArrayCollection();
    }

    public function addModeloMarcaProducto(ModeloMarcaProducto $modeloMarcaProducto)
    {
        $this->modeloMarcaProducto[] = $modeloMarcaProducto;
    }

    public function removeModeloMarcaProducto(ModeloMarcaProducto $modeloMarcaProducto)
    {
        $this->modeloMarcaProducto->removeElement($modeloMarcaProducto);

        return $this;
    }    

    public function getModeloMarcaProducto()
    {
        return $this->modeloMarcaProducto;
    }
}

Through Ajax I made a request to a method that handle multiple values:

foreach ($request->request->get('items') as $item) {
    // delete row if it can be deleted 
}

In the code above, $item['value'] holds negocio.fabricante_modelo_marca_producto.fabricante_producto_solicitud_id values, the idea is to delete each row from the related table (fabricante_modelo_marca_producto) by giving the fabricante_producto_solicitud_id, can any give me some help?

EDIT: find the best approach

Trying to find the best approach I made this piece of code:

foreach ($request->request->get( 'items' ) as $item) {
    $relacion = $this->get( 'database_connection' )->fetchColumn(
        'SELECT COUNT(fabricante_producto_solicitud_id) AS cnt FROM negocio.fabricante_modelo_marca_producto WHERE fabricante_producto_solicitud_id = ?',
        array( $item['value'] )
    );

    if ($relacion === 0) {
        $entFabricanteProductoSolicitud = $em->getRepository(
            "AppBundle:FabricanteProductoSolicitud"
        )->find( $item['value'] );

        try {
            $em->remove( $entFabricanteProductoSolicitud );
            $em->flush();
            array_push( $itemsRemoved, $item['value'] );

            $response['success'] = true;
            $status              = 200;
        } catch ( \Exception $e ) {
            $status = 400;
            dump( $e->getMessage() );

            return new JsonResponse( $response, $status ?: 200 );
        }
    }

    $response['itemsRemoved'] = $itemsRemoved;
}

}

Perhaps it has some issues since I'm writing yet and it's not tested but in this way I can know which item as deleted and which not, right? Is this the right way?


Solution

  • I would do it this way:

    First, retrieve all $fabricanteProductoSolicitud using a join to get their $modeloMarcaProducto in one query:

    Secondly, go through the result and clear the $modeloMarcaProducto persisting the $fabricanteProductoSolicitud (this isn't translated in an access to DB, just marks entities as deleted for Doctrine).

    Third, send the changes to the DB using a flush:

            $em = $this->getDoctrine()->getEntityManager();
            $qb = $em->createQueryBuilder();
            $ret = $qb
                    ->select("u")
                    ->from('MyBundle:FabricanteProductoSolicitud', 'u')
                    ->join("u.modeloMarcaProducto","f")
                    ->add('where', $qb->expr()->in('u.id', ':ids'))
                    ->setParameter('ids',$request->request->get('items'))
                    ->getQuery()
                    ->getResult();
    
            foreach($ret as $fabricantePS) {
                $fabricantePS->getModeloMarcaProducto()->clear();
                $em->persist($fabricantePS);
            }
    
            $em->flush();
    

    This should remove all entities from the joined table with fabricante_producto_solicitud_id in $request->request->get('items')