Car*_*ara 8 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;
...
}
Run Code Online (Sandbox Code Playgroud)
该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;
...
}
Run Code Online (Sandbox Code Playgroud)
您还需要MyOtherTable_Key在数据库模式中,以便它可以正确存储密钥.
请记住始终将对象键设置为属性.一种方法是在构造函数中声明键.
public function __construct($key)
{
$this->key = $key;
}
Run Code Online (Sandbox Code Playgroud)