[英]Doctrine2 QB – how to select entities where OnetoOne entity doesn't exists
I have two entities: 我有两个实体:
class User extends BaseEntity {
/**
* @ORM\OneToOne(targetEntity="Profile", mappedBy="user", cascade={"persist", "remove"})
* @var Profile
*/
protected $profile;
}
class Profile extends BaseEntity {
/**
* @ORM\OneToOne(targetEntity="User", inversedBy="profile", cascade={"persist"})
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
* @var User
*/
protected $user;
}
What I'm trying to do is to SELECT only users
who don't have any profile (so there's no profile
row with user_id=:user_id
in profiles
table). 我正在试图做的是只选择
users
没有任何的简历谁(所以没有profile
一行user_id=:user_id
在profiles
表)。 However, I have no idea how to make my QueryBuilder. 但是,我不知道如何制作我的QueryBuilder。
First, I tried something simple like 首先,我尝试了一些简单的方法
//u as user
$query = $this->er->createQueryBuilder('u');
$query
->join('u.profile', 'p')
->where('u.profile = 1');
But that returns A single-valued association path expression to an inverse side is not supported in DQL queries. Use an explicit join instead.
但这会返回
A single-valued association path expression to an inverse side is not supported in DQL queries. Use an explicit join instead.
A single-valued association path expression to an inverse side is not supported in DQL queries. Use an explicit join instead.
so I suppose there's something wrong with my relationship? 所以我想我的关系有问题吗? I tried to switch
join()
for leftJoin()
but it didn't help either... 我试图将
join()
切换为leftJoin()
但这也没有帮助...
So what's up with this error and how to make proper condition with where()
to tell Doctrine I want only users where there's no profile? 那么,此错误的原因是什么,以及如何使用
where()
来告诉Doctrine我只希望没有配置文件的用户,以使其具有适当的条件?
Here is how I was able to do it. 这就是我能够做到的方式。 Basically I had Domain & Hosting entities and I wanted to select Domains that had no Hosting attached to them in a one to one relationship.
基本上,我具有Domain&Hosting实体,并且我想选择没有一对一关系附加到Hosting的Domains。
$er->createQueryBuilder('d')
->leftJoin('d.hosting', 'h')
->where('h.id is NULL');
Credits for this solution goes to this Answer 此解决方案的功劳归于此答案
Hope it works for you since our situations are almost identical. 希望它对您有用,因为我们的情况几乎相同。
Just check for null
as value of profile
只需检查
null
作为profile
值
//u as user
$query = $this->er->createQueryBuilder('u');
$query
->where('u.profile is NULL');
Try to use repositories, example for UserRepository : 尝试使用存储库,例如UserRepository :
$qb = $this->createQueryBuilder('u');
$e = $qb->expr();
$qb->leftJoin('u.profile', 'p')
->where($e->isNull('p.id'))
Raw query will look like this: 原始查询将如下所示:
SELECT * FROM users AS u LEFT JOIN u.profile AS p WHERE p.id IS NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.