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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失