选择哪种映射类型来处理关联数组?Doctrine ODM

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映射类型才能在数据库中保留键值对吗?

先感谢您,

Andi(来自德国的问候)

5个回答


1
在ODM 2.0之前的版本中,@Hash将提供必要的数据类型。然而,在ODM 2.0之后,@Hash字段被移除了。为了使用它,我们必须使用带有哈希类型的@field。 更多参考,请单击此处。

1

我想你正在寻找哈希数据类型,是吗?

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

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

    /**
     * @MongoDB\Field(type="hash")
    */
    public $field;
}

1
最佳答案是使用哈希类型。但是如果因为某些原因你不想使用哈希类型,你可以像文档中所说的那样使用由Doctrine ODM提供的EmbeddedDocument功能:

如果您使用哈希类型,则关联数组内的值将直接传递给MongoDB,而不经过准备。仅应使用适用于Mongo驱动程序的格式。如果您的哈希包含不适合的值,则应使用嵌入式文档或使用MongoDB驱动程序提供的格式(例如\MongoDate而不是\DateTime)。

因此,您需要在AppBundle\Document\EmbeddedExample.php中创建EmbeddedDocument EmbeddedExample
<?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
}

然后,您可以在Test文档中使用EmbeddedExample。因此,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;

    // ...
}

-5

@Array 应该可以使用。至少在 ORM 中存在等效项 (@Column(type="array"))


4
这是一个真正无用的答案。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接