每当我将 ArrayCollection 与 Doctrine ORM (2.3, PHP > 5.4) 一起使用,并将对象值与集合中的键相关联时(例如当使用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;
...
}
The set
方法工作正常,但是当我检索键入的信息时$myArray
消失了。
如何让 ORM 正确记住密钥?预先谢谢你。
这是通过以下方式解决的:
/** @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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)