php – Doctrine – 存储ArrayCollection键
发布时间:2020-12-13 18:02:53 所属栏目:PHP教程 来源:网络整理
导读:每当我使用带有Doctrine ORM(2.3,PHP 5.4)的ArrayCollection,并将对象值与集合中的键相关联时(例如使用set方法时),值就会正确存储在数据库中.但是当我想从实体中检索集合时,不会检索密钥,而是使用数字索引. 例如,如果我有以下类: /** @Entity */class MyEnt
每当我使用带有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正确记住键?先谢谢你了.
这可以通过以下方式解决:
/** @Entity */ class MyEntity { /** @OneToMany(targetEntity="MyOtherEntity",mappedBy="mainEntity",indexBy="key") */ private $myArray; public function __construct() { $this->myArray = new ArrayCollection(); } public function addOtherEntity($key,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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |