Doctrine - 存储ArrayCollection键

时间:2013-06-25 17:29:13

标签: php orm doctrine-orm

每当我使用带有Doctrine ORM(2.3,PHP> 5.4)的ArrayCollection,并将对象值与集合中的键相关联时(例如使用set方法时),值就会正确存储在数据库中。但是当我想从实体中检索集合时,密钥不会被检索,而是使用数字索引。

例如,如果我有以下类:

/** @Entity */
class MyEntity
{
    /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity") */
    private $myArray;

    public function __construct()
    {
        $this->myArray = new ArrayCollection();
    }

    public function addOtherEntity($key, $value)
    {
        $this->myArray->set($key, $value);
    }

    ...
}

/** @Entity */
class MyOtherEntity
{
    /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */
    private $mainEntity;
    ...
}

set方法正常运行,但当我检索到信息时$myArray中的密钥消失了。

如何让ORM正确记住密钥?先谢谢你。

1 个答案:

答案 0 :(得分:7)

这可以通过以下方式解决:

/** @Entity */
class MyEntity
{
    /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity", indexBy="key") */
    private $myArray;

    public function __construct()
    {
        $this->myArray = new ArrayCollection();
    }

    public function addOtherEntity($key, $value)
    {
        $this->myArray->set($key, $value);
    }

    ...
}

/** @Entity */
class MyOtherEntity
{
    /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */
    private $mainEntity;

    /** @Column(name="MyOtherTable_Key", type="string", unique=true, length=50)
    private $key;
    ...
}

您还需要在数据库架构中使用MyOtherTable_Key,以便它可以正确存储密钥。

请记住始终将对象键设置为属性。一种方法是在构造函数中声明键。

public function __construct($key)
{
    $this->key = $key;
}