【问题标题】:How to populate additive field via JOIN with Doctrine如何通过 JOIN with Doctrine 填充附加字段
【发布时间】:2017-07-21 22:58:14
【问题描述】:

假设我有一个具有多对一关系的实体(带有 EXTRA_LAZY)并且显然是一个连接列。

eg. Article (main entity) -> Author (external entity)

假设我在文章中添加了一个字段author_name,但该字段未映射到 ORM,并且在某些情况下,该字段应包含 article->author->name 值(通常它可以保持为空)。

当我查询文章列表时,我想自动填充该文章作者名称,而无需实现对查询结果的每个元素执行选择的 getter。我希望 Doctrine 在原始查询中通过一个简单的 JOIN 来获取并补充该值...

我不想将获取模式设置为 EAGER 以提高性能,因为在我的项目中作者是一个非常复杂的实体。

这可能吗?

谢谢

【问题讨论】:

  • 我今天检查了所有的 Doctrine 注释,但没有找到任何可以让你这样做的注释。

标签: php mysql join doctrine-orm field


【解决方案1】:

我可能已经找到了解决方案。不知道这是否是最好的方法,但它确实有效。

我在主类中添加了一个字段获取器

public getAuthorName() {
  return $this->author->name
}

在我的上下文中,这个 getter 只会在特定条件下被序列化程序调用。

在我的存储库代码中,我有一个特殊的方法(我对其进行了重构,以便任何方法都可以隐式调用它)在查询时强制填充 Article->author 字段。该方法只需使用查询构建器将 LEFT JOIN 添加到 Author 类,并在 Article->author 上临时将 FetchMode 设置为 EAGER。

最后一个简单的存储库方法可能是这样的

public findAllWithCustomHydration() {
    $qb = $this->createQueryBuilder('obj');
    $qb->leftJoin("obj.author", "a")
       -> addSelect("a"); //add a left join and a select so the query automatically retrive all needed values to populate Article and Author entities
    //you can chain left join for nested entities like the following
    //->leftJoin("a.address", "a_address")
    //-> addSelect("a_address");


    $q = $qb->getQuery()
              ->setFetchMode(Article::class, "author", ClassMetadata::FETCH_EAGER);
   //setFetchMode + EAGER tells Doctrine to prepopulate the entites NOW and not when the getter of  $article->author is called. 
   //I don't think that line is strictly required because Doctrine could populate it at later time from the same query result or maybe doctrine automatically set the field as EAGER fetch when a LEFT JOIN is included in the query, but i've not yet tested my code without this line.

    return $q->getResult();
}

缺点是您必须自定义每个查询,或者更好地为 repo 的每个方法使用 DQL / SQL / QueryBuilder,但是通过良好的重构,对于简单的包含情况,您可以编写一个通用方法来注入该连接field_name 数组基础。

如果您找到更好的方法,希望此帮助并添加您的答案。

附言。我已经在运行中编写了上面的代码,因为现在我不在我的笔记本上,希望它在第一次执行时能工作。

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 2018-12-28
    • 2015-11-21
    • 2013-09-04
    • 2011-11-02
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多