ste
ste

Reputation: 306

Doctrine - Get entity and relationships in one query

Am I missing a point with Doctrine? It's been very useful for some scenarios, but for the basic scenario of retrieving an entity using an Id (say using find() or findOneBy()) why do you see a query being fired off for every relationship to populate the main entity's properties?

Surely with the mapping/annotations I've created, Doctrine should be capable of a few joins and one query, without having to write a DQL query for the retrieval of each entity.

Or, as I'm predicting, have I missed the point somewhere!

Upvotes: 6

Views: 12056

Answers (2)

Dennis Gawrisch
Dennis Gawrisch

Reputation: 1060

Just add the aliases of related entities to select part of your query.

Let’s say, you have Book related one-to-many to Cover, and you want so select some books with their covers.

With query builder, use:

->createQueryBuilder()
->select("book, cover")
->from("Book", "book")
->leftJoin("book.covers", "cover")

With query, use:

SELECT book, cover FROM Book book LEFT JOIN book.covers cover

As the result, you will receive collections of Book with prepopulated $covers collection.

Upvotes: 7

Roberto
Roberto

Reputation: 2236

Because the relationships are hydrated only when needed - by default Doctrine uses a lazy-loading strategy. If you already know that you will access the related entities, you should build a DQL query that retrieves the record AND the related entities.

Upvotes: 1

Related Questions