Doctrine / MongoDB:使用键值对而不是数值数组

时间:2010-12-26 21:29:32

标签: mongodb doctrine

我正在使用Doctrine ODM和MongoDB。我有一个像这样的“产品型号”:

namespace Cms\Model;

/** @Document(collection="products") */
class Product
{
    /** @Id */
    private $id;

    /** @String */
    private $title;

    /** @String */
    private $description;

    /** @Date */
    private $createdAt;

    /** @EmbedMany(targetDocument="Cms\Model\ProductParam") */
    private $params;

    /** @EmbedOne(targetDocument="Cms\Model\Coordinate") */
    private $coordinate;

    public function  __construct()
    {
        $this->details = new \Doctrine\Common\Collections\ArrayCollection();
        $this->params = new \Doctrine\Common\Collections\ArrayCollection();
    }
}

我的ProductParam模型是这样的:

namespace Cms\Model;

/** @EmbeddedDocument */
class ProductParam
{
    /** @String */
    private $type;

    /** @String */
    private $value;
}

当我使用此架构插入文档时,结果如下:

{
   "_id": ObjectId("4d17ac603ffcf6d01300002a"),
   "title": "Peugeot 206 2001-X-Reg, 1.4lx Air-con, 12 months mot, Credit Cards Accepted.",
   "description": "PEUGEOT 206 1.4LX IMMACULATE THROUGHOUT DRIVES ABSOLUTELY SUPERB",
   "params": {
     "0": {
       "type": "carBrand",
       "value": "PEUGEOT"
    },
     "1": {
       "type": "carModel",
       "value": "206 LX"
    }
}

但我需要的是这样的:

{
   "_id": ObjectId("4d17ac603ffcf6d01300002a"),
   "title": "Peugeot 206 2001-X-Reg, 1.4lx Air-con, 12 months mot, Credit Cards Accepted.",
   "description": "PEUGEOT 206 1.4LX IMMACULATE THROUGHOUT DRIVES ABSOLUTELY SUPERB",
   "params": {
     carBrand: "PEUGEOT",
     carModel: "206 LX"
   }
}

我该怎么做?感谢。

2 个答案:

答案 0 :(得分:3)

我建议你不要使用PostLoad,PrePersist等因为它真的很贵,而是使用strategy="set" E.g:

@EmbedMany(targetDocument="Field", strategy="set")

答案 1 :(得分:0)

您可以使用@Hash类型,但它只引用关联数组,而不是另一个对象。但是,您将此与PostLoadPrePersist事件结合使用,以在对象和关联数组之间进行转换。