开发者

Doctrine/MongoDB: Use key-value pairs instead numeric array

I'm using Doctrine ODM with MongoDB. I have a "开发者_JS百科product model" like this:

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();
    }
}

My ProductParam model is like this:

namespace Cms\Model;

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

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

When i insert documents with this schema, the result is this:

{
   "_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"
    }
}

But what i need is like this:

{
   "_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"
   }
}

How can i do this? Thanks.


I suggest you do not use PostLoad, PrePersist etc. as it would be really expensive, instead use strategy="set" E.g:

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


You can use the @Hash type, but it only references an associative array, not another object. But you use this in conjunction with PostLoad and PrePersist events to convert between an object and associative array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜