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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器