删除attribute = x的几行

时间:2014-04-18 07:48:31

标签: symfony doctrine-orm dql doctrine-query

我需要删除image_id = x适用的所有行 像这样

DELETE FROM  `ImageVoters` WHERE image_id =1

如何使用DQL执行此操作?

由于我试图一次删除多行,remove()函数将无法正常工作

EntityManager#remove() expects parameter 1 to be an entity object, array given.

 $em = $this->getDoctrine()->getManager();
 $query = $em->createQuery('SELECT u FROM GabrielUploadBundle:ImageVoters u WHERE u.image_id = 1');
 $db_imageactions = $query->getResult();
 $em->remove($db_imageactions);
 $em->flush();

这是可行的代码

    $qb = $em->createQueryBuilder();
    $qb->delete('GabrielUploadBundle:ImageVoters', 'v')
        ->where($qb->expr()->eq('v.image_id', ':imageId'))
        ->setParameter('imageId', $current_imageId);

    $qb->getQuery()->execute();

2 个答案:

答案 0 :(得分:5)

您可以创建一个ORM queryBuilder,使用内部orm方法创建一个干净/安全的查询对象

$qb->delete('My\Image\Namespace\ImageVoters', 'ivoter')
   ->where($qb->expr()->eq('ivoter.image_id', ':imageId')
   ->setParameter('imageId', 1);

$qb->getQuery()->execute();

答案 1 :(得分:0)

你也可以像这样执行任何原始SQL:

$sql = "DELETE FROM ImageVoters WHERE image_id =".$image_id;
$q = $em->getConnection()->exec($sql);