在条令2 ORM中,我如何在不发出新查询的情况下使用存储库中已经存在的实体


In Doctrine 2 ORM How do I use an entity that is already in my repository without issuing a new query?

假设我提前获取的所有实体

// 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查询来填充我的回购,然后继续询问回购中的实体,而不必每次都访问DB?

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

Doctrine中的存储库是对象存储的门面,而实际上它只是访问数据库的抽象层。它不会"保留"从查询返回的任何对象。

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

虽然没有内置的方法来满足您的要求,但Doctrine确实允许您创建自定义存储库类,您可以在其中自己实现这一点。但是要小心,因为您可能会发现在PHP中的某些查找会比执行SQL查询慢。