php 使用查询构建器删除 Doctrine 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15555042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Doctrine 2 delete with query builder
提问by Constantin
I have two Entities with relation OneToMany, Projectand Services. Now i want to remove all the services by project_id.
我有两个实体与 OneToManyProject和Services. 现在我想通过 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.
此尝试因 Exception 失败Entity Service does not have property project_id。确实,该属性不存在,它仅作为外键存在于数据库表中。
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.
这也会生成一个无效的 DQL 查询。
Any ideas and examples will be welcome.
欢迎任何想法和示例。
回答by andyhassall
You're working with DQL, not SQL, so don't reference the IDs in your condition, reference the object instead.
您正在使用 DQL,而不是 SQL,因此不要在您的条件中引用 ID,而是引用对象。
So your first example would be altered to:
因此,您的第一个示例将更改为:
$qb = $em->createQueryBuilder();
$qb->delete('Services', 's');
$qb->where('s.project = :project');
$qb->setParameter('project', $project);
回答by kdurolek
If you really can't get project object and you have to handle only with id you can use this.
如果您确实无法获取项目对象并且只能使用 id 处理,则可以使用它。
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)
来自学说文档的引用:使用 Doctrine 进行批量删除有两种可能性。您可以发出单个 DQL DELETE 查询,也可以迭代结果一次删除一个。(下面我只粘贴第一个解决方案)
DQL Query The by far most efficient way for bulk deletes is to use a DQL DELETE query.
DQL 查询 迄今为止,批量删除最有效的方法是使用 DQL DELETE 查询。
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.
在实体 TemplateBlock 中,我有一个名为 template 的属性,它映射到 db 中的 template_id。
But I agree that highly preferred way of doing it is using objects.
但我同意高度推荐的做法是使用对象。

