简体   繁体   中英

Doctrine 2 MongoDb ODM references

I have a question related to Doctrine 2 MongoDB ODM in php.

So I have an EntityA and within EntityA I would like to reference EntityB via EntityB 's ObjectId . So in EntityA I have a variableA with the following Docblock: @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.

Basically EntityA looks like this:

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 ?

This is how the ODM works. On the object-side, you add a whole Product to SubCategory .

Your Mongo database will only store the reference, eg (in your Subcategory item)

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

To create the relationship, you simply set your Product into the SubCategory , eg

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

To get the Product ID from SubCategory , you just use

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

(assuming you have the appropriate setter and getter methods defined)


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 ).

Embedded documents are used when you only want that document as part of its parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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