简体   繁体   English

Doctrine 2 MongoDb ODM参考

[英]Doctrine 2 MongoDb ODM references

I have a question related to Doctrine 2 MongoDB ODM in php. 我有一个与php中的Doctrine 2 MongoDB ODM有关的问题。

So I have an EntityA and within EntityA I would like to reference EntityB via EntityB 's ObjectId . 所以我有一个EntityA ,在EntityA中,我想通过EntityBObjectId引用EntityB So in EntityA I have a variableA with the following Docblock: @ODM\\ReferenceOne(targetDocument="EntityB", simple="true") . 所以在EntityA中,我有一个带有以下Docblock的variableA@ODM \\ ReferenceOne(targetDocument =“ EntityB”,simple =“ true”)

The problem is when i call the setMethod it sets the whole of EntityB into EntityA and not just the objectId which is what I would like to do. 问题是,当我调用setMethod时,它将整个EntityB设置EntityA ,而不仅仅是我想做的objectId

Basically EntityA looks like this: 基本上,EntityA看起来像这样:

ENTITYA {
    randomFieldA,
    randomFieldB,
    EntityB ObjectId
}       

Does anyone know if what I want is possible like how I have tried? 有谁知道我想要的东西是否像我尝试过的一样可行? or does someone know a better way? 还是有人知道更好的方法?

Basically like this example: 基本上像这个例子:

/** @Document */
class TopCategory 
{

    /** @EmbedMany(targetDocument="SubCategory") */
    private $subCategories;

}

/** @EmbeddedDocument */
class SubCategory 
{

    /** @ReferenceOne(targetDocument="Product") */
    private $product;

}


/** @Document */
class Product
{

    /** @id */
    private $id;

    /** @String */
    private $name;

}

Now how do i store only the id of the product and not the entire product in subCategory->product ? 现在,我如何仅将产品ID而不是整个产品存储在subCategory->product

This is how the ODM works. 这就是ODM的工作方式。 On the object-side, you add a whole Product to SubCategory . 在对象方面,将整个Product添加到SubCategory

Your Mongo database will only store the reference, eg (in your Subcategory item) 您的Mongo数据库将仅存储参考,例如(在您的“ Subcategory项目中)

"product": {
    "$ref": "Product",
    "$id": ObjectId("4b0552b0f0da7d1eb6f126a1")
}

To create the relationship, you simply set your Product into the SubCategory , eg 要创建关系,您只需将Product设置为SubCategory ,例如

// $product is a persisted Product object
$subcategory->setProduct($product);

To get the Product ID from SubCategory , you just use 要从SubCategory获取Product ID,您只需使用

$productId = $subcategory->getProduct()->getId();

(assuming you have the appropriate setter and getter methods defined) (假设您已定义了适当的settergetter方法)


You use references when you want to create a relationship to a stand-alone document. 当您要创建与独立文档的关系时,可以使用引用 This is particularly true where you may want to link to one document (like your Product ) from many other documents (like your SubCategories ). 在您可能希望从许多其他文档(例如SubCategories )链接到一个文档(例如Product )的情况下尤其如此。

Embedded documents are used when you only want that document as part of its parent. 仅当您希望该文档作为其父文档的一部分时,才使用嵌入式文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM