使用查询构建器删除 Doctrine 2

2022-01-03 00:00:00 php doctrine-orm

我有两个具有 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);

相关文章