Symfony 3.0:在存储库中重用实体

时间:2016-02-28 13:54:00

标签: php symfony

在我的Symfony 3.0项目中,我有一个名为ImageGroups的实体和一个使用ImageGroupsRepository实体的ImageGroups存储库。我还制作了一个Images实体ImagesRepository

ImageGroupsRepository我有一个名为getUserImageGroups的方法,在ImagesRepository上我有一个名为add的方法。

我想问的是如何使用getUserImageGroups中的ImageGroupsRepository方法add中的ImagesRepository

2 个答案:

答案 0 :(得分:4)

A.L给出的答案是正确的,我只是想提供一种替代方法来访问实体管理器,而不必通过var o = { nums : [1,2,3,4], fn : function() { var self = this; this.nums.forEach(function(v) { // "this" in this context would be the window, // but "self" would be the object "o", hence the common use of this hack }); this.nums.forEach((v) => { // "this" in this context, would be the object "o" // that happens because the "this-value" in the fn() function, // ... is the parent object // and the arrow function inherits that this-value }); for (var i=0; i<this.nums.length; i++) { // "this" in this context is what it has always been, // a for-loop has the same this-value as the surrounding scope } } } o.fn(); // called from global context "window" 再次调用该函数:

$this->_em

如果查看documentation for EntityRepository,您会看到class ImagesRepository extends EntityRepository { public function add() { $imagesGroups = $this->_em ->getRepository('AcmeBundle:ImageGroups') ->getUserImageGroups(); // … } } 函数只返回getEntityManager()类的受保护$_em成员。

答案 1 :(得分:3)

在您的存储库中,您可以使用$this->getEntityManager()获取实体管理器,这允许调用getRepository()以获取另一个存储库:

class ImagesRepository extends EntityRepository
{
    public function add()
    {
        $em = $this->getEntityManager();

        $imagesGroups = $em
            ->getRepository('AcmeBundle:ImageGroups')
            ->getUserImageGroups();

        // …
    }
}