12

我有一个关于(顺便说一句真的很棒!)Doctrine ODM 的简单问题。

假设你有一个像这样的文件:

/**
 * @Document
 */
class Test
{
    /** @Id */
    public $id;
    /** @WHICHTYPE */
    public $field = array();
}

现在我想存储一个关联数组,例如

array("test" => "test1", "anothertest" => "test2", ......);

在该类的 $field 属性中。

我知道,MongoDB 没有问题,但是在 Doctrine 中,当我使用 @Collection 或简单地使用 @Field 时,只存储值(例如,在映射驱动程序中使用 array_values 进行集合)。所以存储的值看起来像

array("test1", "test2", ....)

有谁知道我应该使用哪种 Doctrine-ODM 映射类型来保留数据库中的键值对?

先感谢您,

安迪(来自德国的问候)

4

5 回答 5

17

它应该是 Hash 类型:

http://readthedocs.org/docs/doctrine-mongodb-odm/en/latest/reference/annotations-reference.html?highlight=hash#hash

于 2010-11-29T20:35:16.837 回答
1

对于 ODM 2.0 之前的版本,@Hash 将提供必要的数据类型。但是在 ODM 2.0 之后,@Hash 字段被删除。为了使用它,我们必须使用带有哈希类型的@field。供进一步参考[click here][1]

于 2016-09-20T12:23:56.593 回答
0

最好的答案是使用hash type。但是,如果由于某种原因您不想使用hash类型,您可以使用 Doctrine ODM 提供的 EmbeddedDocument 功能,如文档所述:

如果您使用的是哈希类型,则关联数组中的值会直接传递给 MongoDB,而无需进行准备。只应使用适合 Mongo 驱动程序的格式。如果您的哈希包含不合适的值,您应该使用嵌入式文档或使用 MongoDB 驱动程序提供的格式(例如 \MongoDate 而不是 \DateTime)。

因此,您需要在以下位置创建EmbeddedExampleEmbeddedDocument AppBundle\Document\EmbeddedExample.php

<?php

namespace AppBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\EmbeddedDocument()
 */
class EmbeddedExample
{
    /**
     * @MongoDB\Field(type="int")
     */
    protected $some_name;

    // ...
    // getter and setter
}

然后,您可以EmbeddedExample在您的Test文档中使用。所以Test.php文件将与此类似:

<?php

namespace AppBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
* @MongoDB\Document(repositoryClass="AppBundle\Repository\TestRepository")
*/
class Test
{

    /** @MongoDB\EmbedOne(targetDocument="EmbeddedExample") */
    private $field;

    // ...
}
于 2019-07-07T16:21:40.753 回答
0

我认为您正在寻找hash数据类型。你不是吗?

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @Document
 */
class Test
{
    /** @Id */
    public $id;

    /**
     * @MongoDB\Field(type="hash")
    */
    public $field;
}
于 2018-05-11T15:01:01.017 回答
-5

@Array 应该可以工作。ORM 中至少存在一个等价物 (@Column(type="array"))

于 2010-11-16T12:49:20.820 回答