Doctrine 2 delete with query builder

2019-01-25 03:04发布

I have two Entities with relation OneToMany, Project and Services. Now i want to remove all the services by project_id.

First attempt:

$qb = $em->createQueryBuilder();
$qb->delete('Services','s');
$qb->andWhere($qb->expr()->eq('s.project_id', ':id'));
$qb->setParameter(':id',$project->getId());

This attempt fails with the Exception Entity Service does not have property project_id. And it's true, that property does not exists, it's only in database table as foreign key.

Second attempt:

$qb = $em->createQueryBuilder();
$qb->delete('Services','s')->innerJoin('s.project','p');
$qb->andWhere($qb->expr()->eq('p.id', ':id'));
$qb->setParameter(':id',$project->getId());

This one generetate a non valid DQL query too.

Any ideas and examples will be welcome.

2条回答
混吃等死
2楼-- · 2019-01-25 03:09

You're working with DQL, not SQL, so don't reference the IDs in your condition, reference the object instead.

So your first example would be altered to:

$qb = $em->createQueryBuilder();
$qb->delete('Services', 's');
$qb->where('s.project = :project');
$qb->setParameter('project', $project);
查看更多
【Aperson】
3楼-- · 2019-01-25 03:32

If you really can't get project object and you have to handle only with id you can use this.

Citation from doctrine documentation: There are two possibilities for bulk deletes with Doctrine. You can either issue a single DQL DELETE query or you can iterate over results removing them one at a time. (Below I paste only first solution)

DQL Query The by far most efficient way for bulk deletes is to use a DQL DELETE query.

Example that worked in my project

$q = $em->createQuery('delete from AcmeMyTestBundle:TemplateBlock tb where tb.template = '.intval($templateId));
$numDeleted = $q->execute();

In entity TemplateBlock I have property called template which is mapped to template_id in db.

But I agree that highly preferred way of doing it is using objects.

查看更多
登录 后发表回答