繁体   English   中英

Doctrine2 QB –如何选择不存在OnetoOne实体的实体

[英]Doctrine2 QB – how to select entities where OnetoOne entity doesn't exists

我有两个实体:

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

我正在试图做的是只选择users没有任何的简历谁(所以没有profile一行user_id=:user_idprofiles表)。 但是,我不知道如何制作我的QueryBuilder。

首先,我尝试了一些简单的方法

//u as user
$query = $this->er->createQueryBuilder('u');
$query
    ->join('u.profile', 'p')
    ->where('u.profile = 1');

但这会返回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. 所以我想我的关系有问题吗? 我试图将join()切换为leftJoin()但这也没有帮助...

那么,此错误的原因是什么,以及如何使用where()来告诉Doctrine我只希望没有配置文件的用户,以使其具有适当的条件?

这就是我能够做到的方式。 基本上,我具有Domain&Hosting实体,并且我想选择没有一对一关系附加到Hosting的Domains。

$er->createQueryBuilder('d')
                    ->leftJoin('d.hosting', 'h')
                    ->where('h.id is NULL');

此解决方案的功劳归于此答案

希望它对您有用,因为我们的情况几乎相同。

只需检查null作为profile

//u as user
$query = $this->er->createQueryBuilder('u');
$query
    ->where('u.profile is NULL');

尝试使用存储库,例如UserRepository

$qb = $this->createQueryBuilder('u');
$e  = $qb->expr();
$qb->leftJoin('u.profile', 'p')
    ->where($e->isNull('p.id'))

原始查询将如下所示:

SELECT * FROM users AS u LEFT JOIN u.profile AS p WHERE p.id IS NULL;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM