避免 Doctrine 返回所有实体 [英] Avoid Doctrine to return all entities

查看:18
本文介绍了避免 Doctrine 返回所有实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Symfony2/doctrine2,当我们使用 find() 函数根据选择的实体获取特定对象时(如 OneToMany),Doctrine 返回所有其他对象.

Using Symfony2 / doctrine2, while we use the find() function to get a specific object based on the entity selected if there are relations (like OneToMany), Doctrine return all other object.

例如:

$em = $this->get(
         'doctrine.orm.entity_manager', 
          $request->getSession()->get('entity_manager')
);
$product = $em->getRepository('MyBundle:Product')->find($id);

$product 上的结果将是 Product 对象 + 其他链接对象,例如(Store、Category、...等)

The result on $product will be the Product object + other linked objects like (Store, Category, ...etc.)

我们如何控制教义来确定我们需要返回哪个对象.

How can we control doctrine to determinate which object we need to be returned.

我可以使用 Querybuilder,但我正在查看是否有任何功能都是确定的.

I can use Querybuilder, but i am looking if there are any function all determinate.

推荐答案

学说返回所有其他对象

Doctrine return all other object

这不是它的工作方式,至少在默认情况下是这样.

This is not how it works, at least by default.

Doctrine 使用所谓的 延迟加载.
从官方文档中,您有以下示例:

Doctrine uses what is called lazy loading.
From the official documentation, you have the following example:

<?php
/** @Entity */
class Article
{
    /** @Id @Column(type="integer") @GeneratedValue */
    private $id;

    /** @Column(type="string") */
    private $headline;

    /** @ManyToOne(targetEntity="User") */
    private $author;

    /** @OneToMany(targetEntity="Comment", mappedBy="article") */
    private $comments;

    public function __construct {
        $this->comments = new ArrayCollection();
    }

    public function getAuthor() { return $this->author; }
    public function getComments() { return $this->comments; }
}

$article = $em->find('Article', 1);

还有下面的解释:

而不是传给你一个真实的作者实例和一个集合评论 Doctrine 将为您创建代理实例.只有当你第一次访问这些代理,他们将通过EntityManager 并从数据库中加载它们的状态.

Instead of passing you back a real Author instance and a collection of comments Doctrine will create proxy instances for you. Only if you access these proxies for the first time they will go through the EntityManager and load their state from the database.

参考:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entity-object-graph-traversal

有关该主题的更多信息:http://www.doctrine-project.org/blog/doctrine-lazy-loading.html

More information about the topic: http://www.doctrine-project.org/blog/doctrine-lazy-loading.html

这篇关于避免 Doctrine 返回所有实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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