在Doctrine2中从多个关系删除相关实体的行 [英] Delete row from related entity in many to many relationship in Doctrine2
问题描述
我有这个实体:
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;
}
}
通过Ajax我提出了一个处理方法的请求多个值:
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
}
在上面的代码中, $ item ['value']
保存 negocio.fabricante_modelo_marca_producto.fabricante_producto_solicitud_id
值,其想法是删除每行通过给出 fabricante_producto_solicitud_id
的相关表( fabricante_modelo_marca_producto
)可以给我一些帮助吗?
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?
编辑:找到最好的方法
试图找到最好的方法我做了这段代码:
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?
推荐答案
我会这样做:
首先,使用连接检索所有 $ fabricanteProductoSolicitud
,以便在一个查询中获取他们的 $ modeloMarcaProducto
:
First, retrieve all $fabricanteProductoSolicitud
using a join to get their $modeloMarcaProducto
in one query:
其次,查看结果并清除 $ modeloMarcaProducto
坚持 $ fabricanteProductoSolicitud
(这不是在访问数据库的过程中翻译,只是将实体标记为Doctrine删除)。
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).
第三,使用 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();
这应该使用 fabricante_producto_solicitud_id $ c从连接的表中删除所有实体$ c> $
$ request-> request-> get('items')
这篇关于在Doctrine2中从多个关系删除相关实体的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!