在 Doctrine 2 ORM 中,如何使用存储库中已有的实体而不发出新查询?

发布于 2024-11-16 09:09:50 字数 616 浏览 2 评论 0原文

鉴于我预先获取所有实体,

// Get All Users
$qb = $em->createQueryBuilder();
$qb->select("u")->from->("User u");
$q = $qb->getQuery();
// Doesn't this store any entities returned in the repository?
$r = $q->getResult();

如果我随后询问我的存储库,我希望它不必返回数据库来解决我的查询 - 但事实确实如此。这是为什么呢?

// Get a particular user
$user = $em->getRepository('\User')->findByName('JoeBloggs');

// Is generating another query same as above but with 'where' clause...

有没有一种方法可以让我使用一个 DQL 查询来填充我的存储库,然后继续询问存储库中的实体,而不必每次都访问数据库?

顺便说一句,是否有任何方法可以使用多个 DQL 查询来初始填充存储库?

Given that I Fetch all my entities up front

// Get All Users
$qb = $em->createQueryBuilder();
$qb->select("u")->from->("User u");
$q = $qb->getQuery();
// Doesn't this store any entities returned in the repository?
$r = $q->getResult();

If I then interrogate my repository, I would expect it not to have to go back to the database to resolve my query - but it does. Why is this?

// Get a particular user
$user = $em->getRepository('\User')->findByName('JoeBloggs');

// Is generating another query same as above but with 'where' clause...

Is there any way that I can use one DQL query to populate my repo and then continue to interrogate the repo for entities without having to hit the DB every time?

As an aside is there any way to initially populate the repo using more than one DQL query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春风十里 2024-11-23 09:09:50

Doctrine 中的存储库是对象存储的一个外观,而实际上它只是用于访问数据库的抽象层。它不会“保留”从查询返回的任何对象。

Doctrine 跟踪已加载到 UnitOfWork 中的对象,但它保留的唯一索引是标识符。因此,如果您对已加载的对象使用 find() 函数,它将不会访问数据库,但任何其他查询都会访问数据库。

虽然没有内置方法可以完成您所要求的操作,但 Doctrine 确实允许您创建自定义存储库类,您可以在其中自己实现此目的。但要小心,因为您可能会发现 PHP 中的某些查找会比执行 SQL 查询慢。

Repositories in Doctrine are a façade for object storage, when in reality it is just an abstraction layer for accessing the database. It does not "hold on to" any of the objects that are returned from queries.

Doctrine keeps track of objects that have been loaded in the UnitOfWork, but the only index it keeps is on the identifier. So if you are using the find() function for an object that is already loaded, it will not hit the database, but any other query will.

While there is no built-in way to do what you are asking, Doctrine does allow you to create custom repository classes in which you could implement this yourself. Be careful though, as you may find that some of these lookups in PHP will be slower than performing a SQL query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文