php - 在 Doctrine2 DQL 中通过 ManyToOne 关联选择实体

标签 php doctrine-orm

我有两个实体,UserAccount 和 UserEmail。 UserAccount 与 UserEmail 具有 OneToMany 关联。我想要做的是选择具有给定电子邮件的 UserAccount。

如何使用 DQL 生成类似以下 SQL JOIN 查询的内容:

SELECT a.* FROM user_account a
    INNER JOIN user_email e ON e.account_id = a.id
    WHERE e.address = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04776b69616b6a6144617c65697468612a676b69" rel="noreferrer noopener nofollow">[email protected]</a>'

如果我这样做SELECT account, email FROM UserEmail email JOIN email.account account WHERE email.address = :email它给我发回了电子邮件,但这并不是我真正想要的。

我是否只需取回电子邮件,然后从中获取帐户即可?

最佳答案

这就是 fetch-joining全部内容是:您的“电子邮件”对象包含此处的帐户。

SELECT e, a FROM UserEmail e JOIN e.account a WHERE e.address = :email

然后简单地做

$account = $email->getAccount();

执行此操作的另一种方法是选择具有该电子邮件地址的所有帐户:

SELECT a FROM UserAccount a JOIN a.emails e WHERE e.address = :email

这将直接检索帐户对象。

关于php - 在 Doctrine2 DQL 中通过 ManyToOne 关联选择实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12983970/

相关文章:

php - $_FILES 中的某些键为空

php - 与自定义永久链接一起使用时 Wordpress 站点地图 XML 错误

php - 删除 PHP 字符串中的所有不匹配字符?

php - 尝试从命名空间 symfony Controller 调用函数

php - Python 获取 Index Position 比 PHP 慢

symfony - 控制台命令中未调用监听器

php - Symfony2 : Unable to use DoctrineExtensions Mysql Year function

php - 在symfony中获取插入行的主键id

php - Symfony2,创建querybuilder where子句,不为空或不为空

php - 从 MySQL/PHP 中的多个表中删除的正确语法