gpt4 book ai didi

php - 如何使用 Doctrine 通过 JOIN 填充附加字段

转载 作者:行者123 更新时间:2023-11-29 03:22:06 25 4
gpt4 key购买 nike

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

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

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

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

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

这可能吗?

谢谢

最佳答案

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

我在主类中添加了一个字段 getter

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

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

在我的存储库代码中,我有一个特殊的方法(我重构了它以便任何方法都可以隐式调用它)来在查询时强制填充 Article->author 字段。该方法简单地使用 querybuilder 将 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 但是通过良好的重构,对于简单的包含情况,您可以编写一个通用方法来注入(inject)该连接一个 field_name 数组基础。

希望这对您有所帮助,如果您找到更好的方法,请添加您的答案。

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

关于php - 如何使用 Doctrine 通过 JOIN 填充附加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com