mongodb-odm
mongodb-odm copied to clipboard
Mapped ReferenceOne associations are not lazy loaded
Mapped RefereceMany
associations are hydrated as empty PersistentCollection
objects but mapped ReferenceOne
associations are hydrated immediately, causing an extra database query that may not be needed.
I believe ReferenceOne
are lazily loaded unless they're on inverse side?
@malarzm I believe we may be talking about the same thing. When I say, "mapped ReferenceOne association", I mean an association written like, @ReferenceOne(targetDocument="Foo" mappedBy="bar")
. I suppose, technically, one may also refer to that as the inverse side.
Yup, we're talking about same thing then :) I can't seem to find it, but there was a ticket about such thing, in general to achieve such thing we need to extend the proxies to be able to fetch document using arbitrary query, not only by its identifier.
Although I previously discussed a similar issue concerning custom repositories, this particular issue is just about retrieving a document by its identifier.
Note that one of the challenges here are the fact that it's expected that on the document object you can access its methods directly with ->
like a reference, yet you can't just create an odm reference the same way as with a document with a real reference, because you don't even know what the ID is.
And also, coming up with a new lazy ID-less reference class would probably not play along well with Doctrine ODM's local UnitOfWork cache i.e. $referenceWithMappedBy !== $actualSameDocumentAlreadyManaged
By the way at the moment a workaround we are using is avoiding ReferenceOne-mappedBy and just using ReferenceMany-mappedBy instead, and practically ignoring any potentially found additional documents past index 0.
By the way at the moment a workaround we are using is avoiding ReferenceOne-mappedBy and just using ReferenceMany-mappedBy instead, and practically ignoring any potentially found additional documents past index 0.
For now, I'd say this is the recommended way if you want to avoid lazy-loading inverse ReferenceOne
relationships. The problem comes down to proxy objects, which currently assume to always have an identifier and only lazy-loading other fields. However, in order to get the identifier necessary for such a relationship, we have to hit the database, so we might as well hydrate the full document. So until we change the proxy logic, we can't do anything about this without causing multiple database hits for a single document. This is essentially why I've moved this to the 2.x milestone where I'm hoping to have more options with proxy objects (partially hydrated proxies, more complex initializers, etc.).
Any progress since 2017?
@maxgorovenko yes, can't you see how people are rushing to create pull requests for functionality they'd like to have?