【问题标题】:Avoid Doctrine to return all entities避免 Doctrine 返回所有实体
【发布时间】:2013-07-30 18:25:20
【问题描述】:

使用 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 上的结果将是 Product 对象 + 其他链接对象,例如(Store、Category、...等)

我们如何控制教义来确定我们需要归还哪个对象。

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

【问题讨论】:

    标签: object symfony doctrine entity


    【解决方案1】:

    学说返回所有其他对象

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

    Doctrine 使用所谓的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);
    

    以及下面的解释:

    而不是传给你一个真实的作者实例和一个集合 cmets Doctrine 将为您创建代理实例。只有当你 第一次访问这些代理,他们将通过 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】:

    您可以配置extra lazy associations 以避免加载一般关系。

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

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多