duanbigan7765 2013-06-20 10:21
浏览 25
已采纳

在Doctrine2和MongoDB中引用嵌入文档

I have a document User that contains

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

and a document ImageCollection which embed documents called Image

/** 
 * @MongoDB\EmbedMany(targetDocument="Image") 
 */
private $images = array();

and my embed-document Image that contains some usual fields. This is how I try to do the reference (uploader is a reference to some user):

$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]);

the result will be something like the following. The problem is, I dont know why I $ref and $db are correct while $id is null?

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

1条回答 默认 最新

  • duanrong6802 2013-09-01 15:22
    关注

    The problem is that you cannot reference an Embedded Document. You can only reference a Document. Careful reading of the Data Modeling Considerations in the MongoDB documentation reveals that you have to choose between embedding and referencing.

    In general, use Embedded Documents when you only need to access the Embedded Document from it's master Document (one-way has-many relationship). If you need reference a Document from multiple places (it belongs to more than one document) or query the document by itself, use references. There are many questions related to the tradeoffs between referencing and embedding on SO, so here is one question with a very good answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计