5

我正在将 Symfony 2 与 Doctrine MongoDb 捆绑包一起使用。

有两个具有映射的类:

/**
 * @MongoDB\Document
 */
class Consultant
{
    /**
     * @MongoDB\Id(strategy="NONE")
     */
    protected $id;

    /**
     * @MongoDB\EmbedMany(targetDocument="Specialization", strategy="set")
     */
    protected $specs;
}

/**
 * @MongoDB\Document
 */
class Specialization
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\String
     */
    protected $name;

    /**
     * @MongoDB\Boolean
     */
    protected $visible = true;
}

保存顾问后,Mongo 记录如下所示:

{
   "_id": "1",
   "name": "Manager",
   "specs": {
     "0": {
       "_id": ObjectId("50d071ac6146a1f342000001"),
       "name": "Support",
       "visible": false 
    },
     "1": {
       "_id": ObjectId("50d069336146a10244000000"),
       "name": "Orders",
       "visible": false 
    } 
  } 
}

除了冗余字段“可见”之外,一切都很好。

@EmbedMany有没有办法使用注释指定 Doctrine 应该嵌入哪些字段?

4

1 回答 1

6

Specialization 类使用文档映射,该映射不适用于嵌入。您应该为此使用EmbeddedDocument

Given that you want to use the same class on its own and in embedded form, it would be best to create an abstract class annotated with MappedSuperclass. There, you can define any field mappings that should exist on both the document and embedded document. In your case, you could leave visible to be defined on the inheriting document class.

Also, be aware that by using the set strategy, you're storing the embedded collection as an object instead of the usual array. This can have implications if you mean to index fields within the denormalized, embedded documents, as you won't be able to make use of multikey indexing. It's also possible to create gaps among the numeric keys.

于 2012-12-19T21:13:27.250 回答