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

一曲冷凌霜 提交于 2020-01-05 07:41:22

问题


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?


回答1:


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')




回答2:


You can do it in this way,

In Your Controller ajax action:

 foreach ($request->request->get('items') as $item) {
    $em = $this->getDoctrine()->getManager();
    $fabricanteProductoSolicitud = $em->getRepository('YourBundle:FabricanteProductoSolicitud')->find($item['value']);
    $modeloMarcaProductos = $fabricanteProductoSolicitud->getModeloMarcaProducto();
        foreach($modeloMarcaProductos as $modeloMarcaProducto)
        {
            //echo $modeloMarcaProducto->getId();
            $fabricanteProductoSolicitud->removeModeloMarcaProducto($modeloMarcaProducto);
            $em->flush();
        }
    }
 }
 // return response; or exit;

Hope this help to you.

I wonder for better answer from other users.



来源:https://stackoverflow.com/questions/28079661/delete-row-from-related-entity-in-many-to-many-relationship-in-doctrine2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!