2013-07-30 54 views
1

使用Symfony2/doctrine2,雖然我們使用find()函數根據所選實體獲取特定對象,如果存在關係(如OneToMany),Doctrine會返回所有其他對象。避免原則返回所有實體

例如:(存儲,分類,...等)

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

在$產品中的結果將是Product對象+像其他鏈接對象

我們如何控制學說確定我們需要返回哪個對象。

我可以使用Querybuilder,但我看是否有任何功能都確定。

回答

5

主義回報所有其他對象

這不是它是如何工作的,至少在默認情況下。

學說使用了所謂的lazy loading
從官方文檔,你有下面的例子:

<?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); 

而且下面的解釋:

而不是通過你回一個真正的作者實例和 意見收集學說將創建代理實例爲你。只有當你 第一次訪問這些代理時,他們將通過 EntityManager並從數據庫加載它們的狀態。

參考:有關的話題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

+2

呵呵我們在這裏有同樣的想法:) – nifr

3

您可以配置extra lazy associations避免一般關係的負荷。

/** 
* @ManyToMany(targetEntity="CmsUser", mappedBy="groups", fetch="EXTRA_LAZY") 
*/ 
protected $property; 
相關問題