原则 - 在一个查询中获取实体和关系 [英] Doctrine - Get entity and relationships in one query

查看:76
本文介绍了原则 - 在一个查询中获取实体和关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我错过了一个教义的观点吗?对于某些情况来说,这是非常有用的,但是对于使用Id检索实体的基本情况(比如说使用find()或findOneBy()),为什么会看到每个关系都被关闭的查询来填充主实体的属性?



当然,我创建的映射/注释,Doctrine应该能够进行几个连接和一个查询,而无需编写一个DQL查询来检索每个实体。



或者,正如我预测的那样,我错过了某个地方!

解决方案

只需将相关实体的别名添加到选择部分查询。



说,你有预订相关的一对多到封面,你想要这样选择一些书籍的封面



使用查询构建器,使用:

   - > createQueryBuilder ()
- > select(book,cover)
- > from(Book,book)
- > leftJoin(book.cove rs,cover)

使用查询,使用:

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

因此,您将收到 Book 的集合,其中填充了 $ cover collection。 / p>

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!

解决方案

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.

这篇关于原则 - 在一个查询中获取实体和关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆