Doctrine - 存储ArrayCollection键 [英] Doctrine - Store ArrayCollection keys

查看:127
本文介绍了Doctrine - 存储ArrayCollection键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Whenever I use an ArrayCollection with Doctrine ORM (2.3, PHP > 5.4), and associate the object values with a key in the collection (such as when using the set method), the values get stored correctly in the database. But when I want to retrieve the collection from the entity, the keys don't get retrieved and instead they use a numeric index.

例如,如果我有以下课程:

For instance, if I have the following classes:

/** @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 中的密钥已经消失。

The set method works properly, but when I retrieve the information the keys in $myArray are gone.

如何使ORM正确记住键?谢谢你。

How do I make the ORM remember properly the keys? Thank you beforehand.

推荐答案

这是通过以下方式解决的:

This is solved in the following way:

/** @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 在您的数据库模式中,所以它可以正确存储密钥。

You also need MyOtherTable_Key in your db schema so it can store the key properly.

记住要始终将对象密钥设置到属性中。一个方法是在构造函数中声明键。

Remember to always set the object key into the property. One way to do so is to declare the key in the constructor.

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

这篇关于Doctrine - 存储ArrayCollection键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆