gpt4 book ai didi

symfony - 强制 Doctrine 在 JOIN 中加载关联实体

转载 作者:行者123 更新时间:2023-12-04 22:30:47 26 4
gpt4 key购买 nike



最好的方法是什么从查询 JOIN 加载嵌套关联实体的 Doctrine ?

细节

我有多个实体( viewcontentTypeversionsettings ),具有三级关联:

view               (primary entity)
contentType (ManyToOne joined on view.contentTypeId = contentType.id)
version (OneToMany joined on version.viewId = view.id)
settings (OneToOne joined on settings.versionId = version.id)

我有一个列表,可以查询所有版本(不是查看)以获取最近修改的版本。但我从 view 访问属性和 contentTypesettings .我访问 contentType通过 view (所以它有两层深)。当我在循环中引用这些属性时, 我不希望 Doctrine Lazy Loading 每个值与每个循环的 N 个查询。

所以我在查询中加入实体,并选择所有字段。
$versionRepo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion');
$queryBuilder = $versionRepo->createQueryBuilder('e')
->join('e.view', 'view')
->addSelect('view')
->join('view.contentType', 'contentType')
->addSelect('contentType')
->join('e.settings', 'settings')
->where('e.siteId = :siteid')->setParameter('siteId', 1)
->setMaxLimit(25);

第一级链接被正确获取,例如 version.view .然而, Doctrine 处理 version.settings就像一个延迟加载,我将有 25 个额外的查询来加载每个单独的值。

所以即使我加入 settings它仍然是延迟加载。

最佳答案

如果您想避免延迟加载(推荐用于循环),Doctrine 建议您在查询时加入实体。但是您还必须将实体添加到 SELECT 语句中,例如

->join('e.settings', 'settings')
->addSelect('settings')

From the Doctrine Docs on Join

A SELECT query can contain joins. There are 2 types of JOINs: “Regular” Joins and “Fetch” Joins.

Regular Joins: Used to limit the results and/or compute aggregate values.

Fetch Joins: In addition to the uses of regular joins: Used to fetch related entities and include them in the hydrated result of a query.

There is no special DQL keyword that distinguishes a regular join from a fetch join. A join (be it an inner or outer join) becomes a “fetch join” as soon as fields of the joined entity appear in the SELECT part of the DQL query outside of an aggregate function. Otherwise its a “regular join”.



Doctrine 还建议您可以使用 Query Hints “虽然不是所有的列都被提取,但水合物对象。”
$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);

如果您不想加入,这可能是需要考虑的事情。

关于symfony - 强制 Doctrine 在 JOIN 中加载关联实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27072153/

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