简体   繁体   English

重构 Doctrine DQL/SQL

[英]Refactor Doctrine DQL/SQL

I have two entities User and Email , where a user can have multiple emails where only one can be a main email.我有两个实体UserEmail ,其中一个用户可以拥有多封电子邮件,其中只有一个可以作为主电子邮件。

I want to know if there is a DQL query to select the main email if exists otherwise it select to first non-main email.我想知道是否有一个 DQL 查询来选择主电子邮件(如果存在),否则它选择第一个非主电子邮件。

The output should be like this:输出应该是这样的:

[
   [user_id:1, email: 'main@email.com'],
   [user_id:2, email: 'not-main@email.com'],
]

Thanks in advance.提前致谢。

class User 
{ 
    /** @OneToMany */
    protected $emails;
}

class Email 
{
    /** @boolean */
    protected $isMain = 0;

    /** @ManyToOne */
    protected $user;
}

The existing solution that I'm trying to convert to a DQL:我试图转换为 DQL 的现有解决方案:

public function getMainEmail(): ?string
{
    $emails = $this->getEmails();

    if (empty($emails) || 0 === \count($emails)) {
        return null;
    }

    /** @var Email $email */
    foreach ($emails as $email) {
        if (1 === $email->getMain()) {
            return $email->getEmail();
        }
    }

    return $emails->first()->getEmail();
}

Maybe not the kind of solution you are looking for, because it actually doesn't use DQL: You could order the associated collection by your isMain flag.也许不是您正在寻找的那种解决方案,因为它实际上不使用 DQL:您可以通过isMain标志订购关联的集合。

class User 
{ 
    /** 
    * @OneToMany 
    * @OrderBy({"isMain" = "DESC"})
    */
    protected $emails;
}

Calling $emails->first() would then always return the users main address, if there is one with the main flag.调用$emails->first()将始终返回用户的主要地址,如果有一个带有主要标志的地址。

See also:也可以看看:

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

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