Php 条令-存储阵列集合密钥
每当我将ArrayCollection与ORM(2.3,PHP>5.4)结合使用,并将对象值与集合中的键相关联(例如使用Php 条令-存储阵列集合密钥,php,orm,doctrine-orm,Php,Orm,Doctrine Orm,每当我将ArrayCollection与ORM(2.3,PHP>5.4)结合使用,并将对象值与集合中的键相关联(例如使用set方法时),值都会正确地存储在数据库中。但是当我想从实体中检索集合时,不会检索键,而是使用数字索引 例如,如果我有以下类: /** @Entity */ class MyEntity { /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity") */ private $myArra
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正确地记住钥匙?事先谢谢。这可以通过以下方式解决:
/** @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;
...
}
您还需要在db模式中使用MyOtherTable\u键
,以便它能够正确存储键
请记住始终将对象键设置到属性中。一种方法是在构造函数中声明密钥
public function __construct($key)
{
$this->key = $key;
}
这是获得键控响应的解决方案吗?等待什么响应?问题一?措辞可怕。将实体序列化为json时,数组集合由元素值键控。顺便说一句,谢谢。如果对集合调用
toArray()
,则将有一个键值数组,其中的键值与存储在数据库中的键值相同,因此是的,这将在序列化时向JS脚本返回键值数组。如果您需要一个可序列化的类,请始终记住让它实现JsonSerializable
,这是PHP默认库的一部分。顺便说一句,如果它不适合你,请回答,这样我可以给你另一个解决方案。