在Doctrine2和MongoDB中引用一个嵌入文档


Reference a Embed Document in Doctrine2 and MongoDB

我有一个文档User包含

/**
 * @MongoDB'ReferenceOne(targetDocument="Image")
 */
private $image;

和文档ImageCollection,其中嵌入了名为Image

的文档
/** 
 * @MongoDB'EmbedMany(targetDocument="Image") 
 */
private $images = array();

和我的embed-document Image,其中包含一些常见的字段。这就是我如何尝试做引用(uploader是对某个用户的引用):

$rep = $this->dm->getRepository('Document'ImageCollection');
$qb = $rep->createQueryBuilder('Document'ImageCollection')->field('images.uploader.$id')->equals(new 'MongoId($uploader->getId()));
$query = $qb->getQuery(); // get query
$result = $query->execute(); // do query
$arr = $result->toArray(); // get array
$item = array_shift($arr); // get first item of array
$newUser = new Documents'User();
$newUser->setName('Bob King');
$newUser->setImage($item->getImages()[0]);

的结果将如下所示。问题是,我不知道为什么我$ref和$db是正确的,而$id是空的?

{
    "_id": ObjectID("51c2c357fa463404041b55ce"),
    "name": "Bob King",
    "image": {
        "$ref": "Image",
        "$id": null,
        "$db": "db_users_and_images"
    }
}

问题是您不能引用嵌入式文档。您只能引用文档。仔细阅读MongoDB文档中的数据建模注意事项,您必须在嵌入和引用之间做出选择。

一般来说,当你只需要从嵌入式文档的主文档访问它时,使用嵌入式文档(单向多有关系)。如果需要从多个位置引用文档(它属于多个文档)或单独查询文档,请使用引用。关于在SO上引用和嵌入之间的权衡有很多问题,所以这里有一个很好的答案。