简体   繁体   English

Symfony 6 & Doctrine:不循环删除一个元素数组

[英]Symfony 6 & Doctrine: delete an array of elements without looping

$em = $this->doctrine->getManager();
$contact = $em->getRepository(Contact::class)->findby(array('id'=>[1,2,3]));
$em->remove($contact);

will give me an error会给我一个错误

EntityManager#remove() expects parameter 1 to be an entity object, array given. EntityManager#remove() 期望参数 1 为实体 object,给定数组。

All answers I could find advise me to loop through the array and delete every record separately.我能找到的所有答案都建议我遍历数组并分别删除每条记录。 I refuse to do so because I only want to send one statement to the database, resulting in SQL: delete from table where id in (1,2,3)我拒绝这样做,因为我只想向数据库发送一个语句,导致 SQL: delete from table where id in (1,2,3)

I think the easiest way is to use the query builder, instead a loop over the remove function.我认为最简单的方法是使用查询生成器,而不是循环删除 function。

$em = $this->doctrine->getManager();
$qb = $em->getRepository(Contact::class)->createQueryBuilder('c');
$affected = $qb->delete()
        ->where('c.id IN (:ids)')
        ->getQuery()
        ->execute(['ids' => [1,2,3]]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM