引用具有ManyToMany关系的ODM(Document,MongoDB)的ORM(实体)

时间:2016-12-29 11:55:20

标签: symfony orm doctrine mapping doctrine-odm

我正在尝试将我的Symfony 2.6中的ODM(MongoDB)和ORM与文档"Blending ORM and MongoDB ODM"

的引用混合在一起

我有两个实体UserCategory。我还有一份文件Product

在混合ODM和ORM时很明显,可以使用OneToMany或ManyToOne案例轻松解决 - 一方面我们定义了ReferenceOne链接+ field指定identifier="fieldId"fieldId本身,在另一方面,我们定义ReferenceMany)。

我的挑战是让$product->categories填充关系ManyToMany。到目前为止,$product->user$product->userId填充时正常检索。但我无法用$product->categories实现相同的目标。

你能帮我找一个解决方案吗?

/** 
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @var ArrayCollection $products
     * 
     * @Gedmo\ReferenceMany(type="document", class="Document\Product", mappedBy="user")
     */
    protected $products;
}

/** 
 * @Gedmo\Tree(type="nested")
 * @ORM\Entity
 * @ORM\Table(name="categories")
 */
class Category
{
    /**
     * @var ArrayCollection $products
     * 
     * @Gedmo\ReferenceMany(type="document", class="Document\Product", mappedBy="products")
     */
    protected $products;
}

然后我有一个文件

/**
 * @MongoDB\Document
 * @MongoDB\HasLifecycleCallbacks
 */
class Product
{
    /**
     * @Gedmo\ReferenceOne(type="entity", class="Entity\User", inversedBy="products", identifier="userId")
     */
    protected $user;

    /**
     * @MongoDB\Field(name="user_id", type="int")
     */
    protected $userId;

    /**
     * @Gedmo\ReferenceMany(type="entity", class="Entity\Category", mappedBy="products")
     */
    protected $categories = array();

    /**
     * @MongoDB\Collection
     */
    protected $categoryIds = array();

    public function getUser()
    {
        return $this->user;
    }

    public function getCategories()
    {
        return $this->categories;
    }

}

P.S>听众gedmo.listener.referenceutils.listener.reference确实存在。

1 个答案:

答案 0 :(得分:2)

该原则提供了该用例的实际文档:

Blending the ORM and MongoDB ODM

它基本上是学说的参考模型的手动实现。简而言之:您将id(或id列表)存储在通过doctrine映射和保留的属性中。

然后在加载过程中(通过事件侦听器或方法注释),您将获取相应的文档并将它们存储在单独的属性中。然后在刷新过程中(通过事件监听器或方法注释),您将获得(可能已更改的)对象的ID,并将它们放回到您的第一个属性中。

我们多年来一直在我们的核心产品中使用这种方法略有改动的版本,它工作正常,没有任何打嗝和非常透明。

对于更好奇的人:为此建立自定义学说类型也是可能的(从长远来看更难但更方便)。