Doctrine 2 delete with query builder(使用查询构建器删除 Doctrine 2)
问题描述
我有两个具有 OneToMany 关系的实体,Project
和 Services
.现在我想通过 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用查询构建器删除 Doctrine 2


基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01