使用查询构建器删除 Doctrine 2 [英] Doctrine 2 delete with query builder

查看:21
本文介绍了使用查询构建器删除 Doctrine 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有 OneToMany 关系的实体,ProjectServices.现在我想通过 project_id 删除所有服务.

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

第一次尝试:

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

此尝试失败,出现异常 Entity Service does not have property project_id.确实,该属性不存在,它只是在数据库表中作为外键.

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.

第二次尝试:

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

这个也会生成一个无效的 DQL 查询.

This one generetate a non valid DQL query too.

欢迎提供任何想法和示例.

Any ideas and examples will be welcome.

推荐答案

您使用的是 DQL,而不是 SQL,所以不要在您的条件中引用 ID,而是引用对象.

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);

这篇关于使用查询构建器删除 Doctrine 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆